Kotlin – Copy Directory
To copy a directory in Kotlin, you can use the copyRecursively() function of the File class from the java.io package. This function allows for recursively copying a directory, including all its files and subdirectories.
This tutorial demonstrates the use of copyRecursively() to copy a directory in Kotlin with an example.
Steps to Copy a Directory Using File.copyRecursively() in Kotlin
Here’s how to copy a directory recursively using File.copyRecursively():
- Import the
Fileclass from thejava.iopackage. - Specify the source and destination directory paths as
Fileobjects. - Invoke the
copyRecursively()method on the sourceFileobject, passing the destinationFileobject as an argument. - Optionally, handle any exceptions that might occur during the copying process, such as
IOException.
Kotlin Example Program to Copy a Directory
In the following example, we’ll copy a directory named 'dir1' to a new location named 'dir2' using File.copyRecursively().
Main.kt
import java.io.File
fun main() {
val sourceDir = File("dir1") // Replace with your source directory path
val destDir = File("dir2") // Replace with your destination directory path
try {
val result = sourceDir.copyRecursively(destDir, overwrite = true)
if (result) {
println("Directory copied successfully.")
} else {
println("Directory not copied.")
}
} catch (e: Exception) {
println("An error occurred while copying the directory: ${e.message}")
}
}
Output
Directory copied successfully.
The output will indicate whether the directory was successfully copied. The overwrite = true argument allows existing files in the destination directory to be overwritten.
Summary
In this tutorial, we explored how to copy a directory in Kotlin using the File.copyRecursively() method.