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

There are several ways to rename a file and/or moving it to a different directory in plain Java and using third-party libraries. These are discussed below in detail:

1. Using NIO

java.nio.file.Files provides several static methods that operate on files, directories, or other types of files. To move a file to a target file, we can use its move() method. The implementation is platform-independent, but it doesn’t fail if the file attributes are not copied. Javadoc guarantees only the last-modified-time to be copied to the new file.

This method takes the path to the file to move, the path to the target file, and an optional parameter to specify how the move is performed. By default, moving fails if the target file already exists unless the REPLACE_EXISTING option is specified. If the source and target are the same files, the method completes without moving the file. If either the source file or the destination directory does not exist, java.nio.file.NoSuchFileException is thrown.

Download Code

2. Using Guava Library

Guava’s Files class has several utility methods for working with files. We can use its move() method, which moves a file from one path to another. If the destination file exists, then that file will be overwritten with the contents and file attributes of the source file.

This method doesn’t create the directory holding the destination file if it does not exist. It throws java.io.FileNotFoundException if the source file doesn’t exist and java.io.IOException in case of an I/O error. If to and from refer to the same file, java.lang.IllegalArgumentException is thrown.

Download Code

3. Using Apache Commons IO

We can also use the FileUtils class from Apache Commons IO library that has the moveFile() method, which moves a file to the destination location.

The major advantage of using Apache Commons IO is that the directory holding the destination file is created if it does not exist. It works even when the destination file is on another file system.

If the target file exists or the destination file and the source file are the same, this method throws org.apache.commons.io.FileExistsException. If the source file doesn’t exist, java.io.FileNotFoundException is thrown. If an IO error occurs while moving the file, a java.io.IOException is thrown.

Download Code

4. Using renameTo() method

We can also use the renameTo() method of the File class, which moves a file on the same file system.

The usage of this method is not recommended as it is platform-dependent, non-atomic, and fails if the destination file already exists. We should always check the return value of this method to ensure that the move operation was successful as no exception is thrown on its failure.

Download Code

That’s all about moving a file in Java.

 
Also See:

Move a directory in Java

Copy a file in Java