Java Files move()

In this guide, you will learn about the Files.move() method in Java programming and how to use it with an example.

1. Files move() Method Overview

Definition:

The Files.move() method is used to move or rename a file to a target file. If the target file exists, it can be replaced if the appropriate options are provided.

Syntax:

static Path move(Path source, Path target, CopyOption... options)

Parameters:

- source: the path to the source file to move.

- target: the path to the target file.

- options: options specifying how the move is to be performed. Common options include REPLACE_EXISTING (allows replacing the existing file) and ATOMIC_MOVE (ensures the move is performed as an atomic file system operation).

Key Points:

- If the target file exists and the REPLACE_EXISTING option is not provided, the move operation fails.

- By default, the move method attempts to move the file to the target file, failing if the target file exists. The move is not atomic unless both the source and target are on the same file store and the ATOMIC_MOVE option is provided.

- Moving a file will also move its associated metadata, such as timestamps.

- It can move both files and directories.

2. Files move() Method Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FilesMoveExample {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("source.txt");
        Path targetPath = Paths.get("target.txt");

        try {
            // Move source.txt to target.txt, replacing the target.txt if it exists
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File moved successfully!");
        } catch (IOException e) {
            System.out.println("Failed to move the file: " + e.getMessage());
        }
    }
}

Output:

File moved successfully!

Explanation:

In the example, the file source.txt is moved to target.txt using the Files.move() method. If target.txt already exists, it will be replaced due to the StandardCopyOption.REPLACE_EXISTING option. The result is printed to the console, indicating whether the file was moved successfully or if an error occurred.

Comments