java-how-to-rename-or-move-a-file
Java – Rename or Move a File
1. Overview
In this quick tutorial, we’re going to look at renaming / moving a File in Java – first using JDK 6, then JDK 7 with NIO, Google Guava and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” series here on Baeldung.
Further reading:
Introduction to the Java NIO2 File API
A quick and practical guide to Java NIO2 File API
2. With JDK 6
@Test
public void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
if (!isMoved) {
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
}
}
In this example – the file to be moved does exist, as well as the target directory.
Note that renameTo() only throws two types of exceptions – SecurityException – if a security manager denies writing access to either the source or to the destination, and NullPointerException – in case if parameter target is null. If the target does not exist in a file system – no exception will be thrown – and you will have to check the returned success flag of the method.
3. With JDK 7
@Test
public void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
Path fileToMovePath =
Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
Path targetPath = Paths.get("src/main/resources/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
In JDK7 the NIO package was significantly updated, and the Path added – this provides methods for convenient manipulation of File System artifacts.
Note that, similarly to the previous example – both the file and the target directory should exist.
4. With Guava
@Test
public void givenUsingGuava_whenMovingFile_thenCorrect()
throws IOException {
File fileToMove = new File("src/test/resources/fileToMove.txt");
File destDir = new File("src/test/resources/");
File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.move(fileToMove, targetFile);
}
Again, in this example, the file to be moved and the target directory need to exist.
5. With Commons IO
@Test
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.moveFile(
FileUtils.getFile("src/test/resources/fileToMove.txt"),
FileUtils.getFile("src/test/resources/fileMoved.txt"));
}
This one line will, of course, allow both moving or renaming – depending if the target directory is the same or not.
Alternatively – here’s a solution for moving specifically, also enabling us to automatically create the destination directory if it doesn’t already exist:
@Test
public void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.moveFileToDirectory(
FileUtils.getFile("src/test/resources/fileToMove.txt"),
FileUtils.getFile("src/main/resources/"), true);
}