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.

Download Code

 
This is equivalent to the following code using loops:

Download Code

That’s all about copy a directory in Kotlin.