Move a directory in Kotlin
This post will discuss how to move a directory in Kotlin.
1. Using Files.move() function
The standard solution for moving a directory in Kotlin is using the function Files.move(). It takes the path of the directory to be moved, the destination path, and an optional parameter to specify the move behavior. By default, the moving fails if the destination exists beforehand, unless the REPLACE_EXISTING option is used.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.StandardCopyOption fun main() { val from = File("/path/to/src") val to = File("/path/to/dest") try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) println("Directory moved successfully.") } catch (ex: IOException) { ex.printStackTrace() } } |
The following solution iterates over files in the source directory and moves them individually. If the directory contains any subdirectories, recursively process all files within the subdirectory.
|
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 27 28 29 30 |
import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption private fun moveDir(src: Path, dest: Path): Boolean { if (src.toFile().isDirectory) { for (file in src.toFile().listFiles()) { moveDir(file.toPath(), dest.resolve(src.relativize(file.toPath()))) } } return try { Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING) true } catch (e: IOException) { false } } fun main() { val from = File("/path/to/src") val to = File("/path/to/dest") val success = moveDir(from.toPath(), to.toPath()) if (success) { println("File Moved Successfully") } else { println("File Moved Failed") } } |
2. Using File#renameTo() function
We can also use the File#renameTo() function, which can move a directory within the same file system. However, this operation is platform-dependent, non-atomic, and fails when the destination directory already exists. Since it doesn’t even throw an exception on failure, always check the return value to ensure that the move operation is successful.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.File fun main() { val from = File("/path/to/src") val to = File("/path/to/dest") val success = from.renameTo(to) if (success) { println("Directory Moved Successfully") } else { println("Directory Moved Failed") } } |
That’s all about moving 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 :)