Files.move: Moving and Renaming Files
What you'll learn: How to move or rename files using Files.move(), including atomic move guarantees and cross-filesystem limitations.
The Core Concept
The Files.move() method serves two purposes: physically moving a file from one location to another, and renaming files (which is essentially moving within the same directory). Think of it like cutting and pasting a file in your file explorer, versus simply renaming it in place—both operations use the same underlying mechanism.
Basic Syntax
Path source = Paths.get("data.txt");
Path destination = Paths.get("backup/data.txt");
Files.move(source, destination);
This moves data.txt into the backup directory. To rename a file, simply change the filename:
Path oldName = Paths.get("draft.txt");
Path newName = Paths.get("final.txt");
Files.move(oldName, newName); // Rename in same directory
Atomic Move Guarantees
Use StandardCopyOption.ATOMIC_MOVE to ensure the operation completes entirely or not at all—no partial moves:
Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE);
This guarantees that observers will never see an incomplete file at the destination. However, atomic moves only work within the same filesystem. Attempting an atomic move across different drives or partitions will throw an AtomicMoveNotSupportedException.
Cross-Filesystem Limitations
When moving files between different filesystems (e.g., from C:\ to D:\ on Windows, or across different mounted drives), Java must copy-then-delete rather than performing a true move. Atomic moves are impossible in this scenario because they require filesystem-level support.
Key Takeaway: Files.move() efficiently moves or renames files, with ATOMIC_MOVE providing all-or-nothing guarantees within the same filesystem—but cross-filesystem moves cannot be atomic and involve copy-delete operations instead.