Moving a file from one path to another is a day-to-day task. It becomes hectic sometimes if you have a complicated file hierarchy. Also, navigating from the source path to the destination path again and again consumes a lot of time. However, you can automate this process by creating a Java program and passing it the source and destination paths to get the job done in a matter of seconds.
Java provides different file-handling classes and supports third-party libraries as well. So, in this post, we will illustrate a couple of built-in methods and a couple of third-party approaches to moving a file using Java.
Method 1: Moving File in Java Using Files.move()
The Files class in Java offers a static method named “move()” that renames or moves a file to a target file/location. To move a file using this method, use the following signature:
Files.move(Path sourceFile, Path targetFile, CopyOption..options);
Here,
- The “sourceFile” is a file that needs to be moved.
- The “targetFile” is a location where the “sourceFIle” will be moved.
- The “options” represent how the file will be moved.
Let’s learn this method via the following example.
Example 1: Move a File Using File Class
First, import the required classes from the respective packages using the “import” statement:
import java.io.*;
import java.nio.file.*;
public class MoveFileJava {
public static void main(String[] args)
{
File sourceFile = new File("C:\\Users\\HP\\Downloads\\Anees\\greetings.txt");
File destFile = new File("C:\\Users\\HP\\Downloads\\Asghar\\greetings.txt");
try {Files.move(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File Moved Successfully!");
}
catch(IOException excep)
{
excep.printStackTrace();
}
}
}
In the main() method:
- Use the File class to specify the source and destination addresses.
- Now use a try-catch block and specify the code within the try block to move a file; in the catch block, write the code to deal with the potential exceptions.
- Note that, in the try block we use the “move()” method with the “toPath()” method to convert the source and destination to the Path object. While the “StandardCopyOption.REPLACE_EXISTING” is an enum constant used to replace the destination file with the source file if it already exists.
On execution, we get the following response, which indicates that the source file has been successfully transferred to the destination:
We execute the same code one more time, as a result, an error occurs, which indicates that the source file doesn’t exist (as it has been already moved from the source to the destination):
Example 2: Move a File Using Path Class
You can also use the Path class with the move() method to move a file from one location to another:
import java.io.*;
import java.nio.file.*;
public class MoveFileJava {
public static void main(String[] args){
try {Path moveFile = Files.move(Paths.get("C:\\Users\\HP\\Downloads\\SourceDir\\greetings.txt"),
Paths.get("C:\\Users\\HP\\Downloads\\DestDir\\greetings.txt"));
if (moveFile != null) {
System.out.println("Congrats! File Moved successfully");
}
}catch(IOException excep){
System.out.println("File Not Found!");
}
}
}
Here, in the above code,
- The Files.move() method is invoked to move a file “greetings.txt” from the source path to the destination path.
- Within the move() method, the paths.get() method creates the path object for the source and destination files.
- The if statement ensures that the file has been successfully moved and as a result, it shows a message: “Congrats! File moved Successfully”:
The catch block catches the IOException if the file doesn’t exist at the source location and shows the following message on the console:
Method 2: Moving File in Java Using File.renameTo()
The renameTo() method of the File class renames the file’s abstract path name to a given file name. You can also use this method to move a file from one location to another. For this purpose, use the below signature:
sourcePath.renameTo(destinationPath);
Where “sourcePath” and “destinationPath” are file objects representing the source and destination files.
Let’s learn how the renameTo() method works using the below coding example:
import java.io.*;
import java.nio.file.*;
public class MoveFileJava {
public static void main(String[] args) throws FileSystemException {
File sourceFile = new File("C:\\Users\\HP\\Downloads\\SourceDir\\greetings.txt");
File destFile = new File("C:\\Users\\HP\\Downloads\\DestDir\\greetings.txt");
boolean fileMoved = sourceFile.renameTo(destFile);
if (fileMoved) {
System.out.println("File Moved Successfully");
}
else {
throw new FileSystemException("Error! Try Again");
}
}
}
The above code,
- Uses the File class to specify the source and destination file paths.
- Next, the renameTo() method moves the “sourceFile” to “destFile”. It will retrieve “true” if the file successfully moves, otherwise false.
- The if-else statement checks if the file is moved or not and displays the message accordingly:
If something goes wrong, the else block shows the following exception using the “FileSystemException”:
Method 3: Moving File in Java Using Guava Library
Other than core/plain Java classes, you can also use third-party libraries like Guava. But to use this library, first, add the below-given dependency into your Maven project (in the pom.xml file):
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.3-jre</version>
</dependency>
Now import the File and IOException classes from the “java.io” package:
import java.io.File
import java.io.IOException;
public class MoveFileGuava {
public static void main(String[] args) {
File sourceFile = new File("C:\\Users\\HP\\Downloads\\SourceDir\\greetings.txt");
File destFile = new File("C:\\Users\\HP\\Downloads\\DestDir\\greetings.txt");
try{
com.google.common.io.Files.move(sourceFile, destFile);
System.out.println("File Moved Successfully!");
}
catch(IOException excep){
System.out.println("File Not Found! Try Again");
}
}
}
The above code:
- Uses the File() constructor to create the File instances that represent the source and destination files.
- The try block invokes the “move()” method of the Guava’s Files class. As a result, this method will move the sourceFile to the destFile:
If the file is not found in the source location, the following exception occurs:
Method 4: Moving File in Java Using Apache Commons IO
Another third-party library “Apache Commons IO” can also be used to move a file from one location to another. Similar to the Guava library, when using the Apache Commons library, its respective dependency also needs to be added to the “pom.xml” file of your Maven project:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
</dependency>
Now import the essential classes into your Java application, including the FileUtils class from the Apache Commons:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class MoveFileApache {
public static void main(String[] args) {
File sourceFile = new File("C:\\Users\\HP\\Downloads\\SourceDir\\greetings.txt");
File destFile = new File("C:\\Users\\HP\\Downloads\\DestDir\\greetings.txt");
try {
FileUtils.moveFile(FileUtils.getFile(sourceFile), FileUtils.getFile(destFile));
System.out.println("File Moved Successfully!");
} catch (IOException excep) {
System.out.println("File Not Found! Try Again");
}
}
}
The above code,
- Uses the getFile() method of the FileUtils class to get the source and the destination addresses.
- After this, the moveFile() method is invoked to move the sourceFile to desFile.
- If the desired file exists at the source address, the selected file will be moved and the following message will be displayed on the console:
If the desired file doesn’t exist, the following message appears on the console:
That’s all from moving a file from one directory to another using Java.
Conclusion
To move a file using Java, you can use built-in methods like “move()” and “renameTo()”. Also, you can use the move() and moveFile() methods of third-party libraries like Guava and Apache Commons, respectively. Among all these approaches, the most convenient method is the move() method of the built-in Files class that moves or renames the given file to the target file.