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 a directory as well using the Files.move() method. Here is an example:

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);
        }
    }
}