Java – Rename or Move a File

1. Overview

In this quick tutorial, we’re going to look at renaming / moving a File in Java.

We’ll first look into using the Files and Path classes from NIO, then the Java File class, Google Guava, and finally the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

2. Setup

In the examples, we’ll use the following setup, which consists of 2 constants for the source and destination file name and a clean-up step to be able to run the tests multiple times:

private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt";
private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt";

@BeforeEach
public void createFileToMove() throws IOException {
    File fileToMove = new File(FILE_TO_MOVE);
    fileToMove.createNewFile();
}

@AfterEach
public void cleanUpFiles() {
    File targetFile = new File(TARGET_FILE);
    targetFile.delete();
}

3. Using the NIO Paths and Files Classes

Let’s start by using the Files.move() method from the Java NIO package:

@Test
public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException {
    Path fileToMovePath = Paths.get(FILE_TO_MOVE);
    Path targetPath = Paths.get(TARGET_FILE);
    Files.move(fileToMovePath, targetPath);
}

In JDK7 the NIO package was significantly updated, and the Path class added. This provides methods for convenient manipulation of File System artifacts.

Note that both the file and the target directory should exist.

4. Using the File Class

Let’s now look at how we can do the same using the File.renameTo() method:

@Test
public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException {
    File fileToMove = new File(FILE_TO_MOVE);
    boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE));
    if (!isMoved) {
        throw new FileSystemException(TARGET_FILE);
    }
}

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
  • NullPointerException – in case the 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.

5. Using Guava

Next – let’s take a look at the Guava solution, which provides a convenient Files.move() method:

@Test
public void givenUsingGuava_whenMovingFile_thenCorrect()
        throws IOException {
    File fileToMove = new File(FILE_TO_MOVE);
    File targetFile = new File(TARGET_FILE);

    com.google.common.io.Files.move(fileToMove, targetFile);
}

Again, in this example, the file to be moved and the target directory need to exist.

6. With Commons IO

Finally, let’s take a look at a solution with Apache Commons IO – probably the simplest one:

@Test
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
    FileUtils.moveFile(FileUtils.getFile(FILE_TO_MOVE), FileUtils.getFile(TARGET_FILE));
}

This one line will, of course, allow both moving or renaming, depending on 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);
}

6. Conclusion

In this article, we looked at different solutions for moving a file in Java. We focused on renaming in these code snippets, but moving is, of course, the same, only the target directory needs to be different.

The code for the examples is available over on GitHub.

Related posts:

Spring REST with a Zuul Proxy
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Spring Boot - Unit Test Cases
A Guide to Java 9 Modularity
String Initialization in Java
Java 8 Collectors toMap
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
The Java 8 Stream API Tutorial
Introduction to Eclipse Collections
LinkedList trong java
Biểu thức Lambda trong Java 8 – Lambda Expressions
Mệnh đề if-else trong java
A Guide to the Java ExecutorService
Java Program to Check whether Graph is a Bipartite using DFS
Spring – Injecting Collections
Deploy a Spring Boot App to Azure
Hướng dẫn Java Design Pattern – Proxy
Spring Security Registration – Resend Verification Email
Semaphore trong Java
Spring Boot - CORS Support
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Write/Read cookies using HTTP and Read a file from the internet
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Java Program to Implement LinkedTransferQueue API
Logging a Reactive Sequence
Java Program to Find Minimum Element in an Array using Linear Search
Serve Static Resources with Spring
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Netflix Archaius with Various Database Configurations