Copy a directory in Kotlin
This post will discuss how to copy a directory in Kotlin. The solution should copy the specified directory, and all its child directories and files, to the specified destination.
In Kotlin, you can walk the file tree in a depth-first manner using the Files.walk(…) function, and then copy each file to the target directory using the Files.copy(…) function. If the destination directory already exists, the copying fails, unless the StandardCopyOption.REPLACE_EXISTING option is provided. If the destination directory is not empty, then DirectoryNotEmptyException is thrown.
The following code demonstrates the usage of the Files.walk(…) with Files.copy(…) function to recursively copy contents of the source directory to the destination directory. You may also use the Files.walkFileTree(…) function to walk the file tree.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption fun copyDir(src: Path, dest: Path) { Files.walk(src).forEach { Files.copy(it, dest.resolve(src.relativize(it)), StandardCopyOption.REPLACE_EXISTING) } } fun main() { val from = File("/var/kotlin/") val to = File("/var/bak/kotlin/") try { copyDir(from.toPath(), to.toPath()) println("Copying succeeded.") } catch (ex: IOException) { ex.printStackTrace() } } |
This is equivalent to the following code using loops:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import kotlin.streams.toList fun copyDir(src: Path, dest: Path) { val sources = Files.walk(src).toList() for (source in sources) { Files.copy(source, dest.resolve(src.relativize(source)), StandardCopyOption.REPLACE_EXISTING ) } } fun main() { val from = File("/var/kotlin/") val to = File("/var/bak/kotlin/") try { copyDir(from.toPath(), to.toPath()) println("Copying succeeded.") } catch (ex: IOException) { ex.printStackTrace() } } |
That’s all about copy a directory in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)