Java Files.move
Move or rename an entry using an explicit destination.
A simple example
Files.move
- Start with A file named a.txt
- Do this Rename it to b.txt
- Result b.txt holds the original contents
Syntax
public static Path move(Path source, Path target, CopyOption... options) throws IOException
JDK 21 declarations (1)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPublish the signed attendance sheet
A class representative edits a draft attendance sheet until it is signed. Once it is ready, the publishing step gives it its final name in the same folder and checks both names.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path draft = Files.writeString(desk.resolve("draft.txt"), "signed");
Path finalCopy = Files.move(draft, desk.resolve("attendance.txt"));
System.out.println(Files.notExists(draft));
System.out.println(Files.readString(finalCopy));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true signed
The content is now reachable through the final name and the old name is absent.
Protect an already published report
A tutor has already published one report under the final filename. A second draft must stay available for review when a move without replacement encounters the occupied destination.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path finalCopy = Files.writeString(desk.resolve("report.txt"), "approved");
Path draft = Files.writeString(desk.resolve("draft.txt"), "revised");
try { Files.move(draft, finalCopy); }
catch (FileAlreadyExistsException e) {
System.out.println(Files.readString(finalCopy));
System.out.println(Files.readString(draft));
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
approved revised
With this default local move the existing destination is preserved and the draft remains available.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Rename the draft to its final name. What text can the next shift read under that name?
What to watch for
Atomic moves are optional and can be unsupported across stores. The default move should not be used to silently replace an existing report.