Java — How to move or rename a File or Directory | Code Factory

Code Factory
2 min readJul 21, 2020

--

Donate : Link

WordPress Blog : Link

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.

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class MoveFileExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder2/test.txt");
try {
Files.move(sourceFilePath, targetFilePath);
System.out.println("Done");
} 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("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder1/test1.txt");
/* test.txt will be renamed to test1.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.

Here is an example of moving or renaming a directory:

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class MoveDirectoryExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/folder1.1");
Path targetFilePath = Paths.get("folder/folder2/folder1.1");
try {
Files.move(sourceFilePath, targetFilePath);
System.out.println("Done");
} catch (FileAlreadyExistsException ex) {
System.out.println("Target file already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

--

--