How to move or rename a File or Directory in Java

In this quick and short article, you’ll learn how to move or rename a file or directory in Java.

Java Move or Rename File using Files.move()

You can use Java NIO’s Files.move() method to copy or rename a file or directory.

import java.io.IOException;
import java.nio.file.*;

public class MoveFileExample {
    public static void main(String[] args) {

        Path sourceFilePath = Paths.get("./foo.txt");
        Path targetFilePath = Paths.get(System.getProperty("user.home") + "/Desktop/foo.txt");

        try {
            Files.move(sourceFilePath, targetFilePath);
        } catch (FileAlreadyExistsException ex) {
            System.out.println("Target file already exists");
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

The Files.move() method will throw FileAlreadyExistsException if the target file already exists. If you want to replace the target file then you can use the REPLACE_EXISTING option like this -

Files.move(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);

If you want to rename a file, then just keep the source and target file locations same and just change the name of the file:

Path sourceFilePath = Paths.get("foo.txt");
Path targetFilePath = Paths.get("bar.txt");

// foo.txt will be renamed to bar.text
Files.move(sourceFilePath, targetFilePath);

Java move or rename a directory

You can move or rename an empty directory using the Files.move() method. If the directory is not empty, the move is allowed when the directory can be moved without moving the contents of that directory.

To move a directory with along with its contents, you would need to recursively call move for the subdirectories and files. We will look at this in another article.

Here is an example of moving or renaming a directory:

import java.io.IOException;
import java.nio.file.*;

public class MoveDirectoryExample {
    public static void main(String[] args) {

        Path sourceFilePath = Paths.get("/Users/callicoder/Desktop/media");
        Path targetFilePath = Paths.get("/Users/callicoder/Desktop/new-media");

        try {
            Files.move(sourceFilePath, targetFilePath);
        } catch (FileAlreadyExistsException ex) {
            System.out.println("Target file already exists");
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}