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

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()

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

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