How to copy a directory and its contents in Kotlin
How to copy a directory and its contents in Kotlin.
Here's a step-by-step tutorial on how to copy a directory and its contents in Kotlin:
- Import the necessary libraries:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
- Define a function to copy the directory and its contents:
fun copyDirectory(sourceDir: File, destinationDir: File) {
// Create the destination directory if it doesn't exist
if (!destinationDir.exists()) {
destinationDir.mkdir()
}
// Get a list of all files and directories in the source directory
val files = sourceDir.listFiles()
// Iterate through the files and directories
for (file in files) {
val newFile = File(destinationDir, file.name)
// If the current item is a directory, recursively call the function
if (file.isDirectory) {
copyDirectory(file, newFile)
} else {
// If the current item is a file, copy it to the destination directory
Files.copy(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
}
}
}
- Call the
copyDirectoryfunction with the source and destination directories:
val sourceDir = File("path/to/source/directory")
val destinationDir = File("path/to/destination/directory")
copyDirectory(sourceDir, destinationDir)
In the above example, make sure to replace "path/to/source/directory" and "path/to/destination/directory" with the actual paths of the source and destination directories.
The copyDirectory function first checks if the destination directory exists. If not, it creates it. It then gets a list of all files and directories in the source directory. For each item, it checks if it's a directory. If it is, it recursively calls the copyDirectory function with the subdirectory and a new destination directory. If it's a file, it copies it to the destination directory using the Files.copy method.
By following these steps, you can easily copy a directory and its contents in Kotlin.