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.

Download Code

 
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.

Download Code

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.

Download Code

That’s all about moving a directory in Kotlin.