This post will discuss how to move a directory in Java from one path to another.

There are several ways to move a directory in plain Java and using third-party libraries. These are discussed below in detail:

1. Using NIO

Since Java 1.7, JDK has java.nio.file.Files, which offers several static methods to operate on files and directories. We can use its move(Path source, Path target, CopyOption… options) method to move a directory.

This method takes the directory path to be moved, the path to the target directory, and an optional parameter to specify how the move is performed. By default, moving fails if the target directory already exists unless the REPLACE_EXISTING option is specified. If the source and target refer to the same directory, the method completes without moving the directory. If the source directory doesn’t exist, java.nio.file.NoSuchFileException is thrown.

Download Code

2. Using Apache Commons IO

Apache Commons IO’s FileUtils class has several utility methods for working with files. We can use its moveDirectory(File srcDir, File destDir) method to move a directory.

If the destination directory already exists, then this method throws org.apache.commons.io.FileExistsException. If the source directory doesn’t exist, java.io.FileNotFoundException is thrown. If an IO error occurs while moving the directory, java.io.IOException is thrown.

The major advantage of using Apache Commons IO is that it works even when the destination is on another file system.

Download Code

3. Using renameTo() method

We can also use the renameTo(File dest) method of the File class, which can move a directory within the same file system.

This method is platform-dependent, non-atomic, and fails if the destination exists beforehand. It doesn’t even throw an exception on failure. Therefore, we should always check the return value of this method to ensure that the move operation was successful.

Download Code

4. Custom move routine

Finally, we can write our own routine to move a directory. The idea is to iterate over files in the source directory and individually move them. If the directory contains any subdirectories, perform this recursively. Here’s a working code:

Download Code

That’s all about moving a directory in Java.

 
Also See:

Move a file in Java