Files Copy Move Atomic Replace
Copy and move files with the NIO Files API using REPLACE_EXISTING and ATOMIC_MOVE options so interrupted operations leave no partial state.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class StagePromotion {
public static void main(String[] args) throws IOException {
Path staging = Files.createTempFile("deploy-", ".tmp");
Path release = staging.resolveSibling("release.txt");
Files.writeString(staging, "build 2026-11-09\nchecksum ok\n");
// 拷贝:显式声明覆盖语义
Files.copy(staging, release, StandardCopyOption.REPLACE_EXISTING);
// 原子改名:同目录内 promote,绝不出现半写状态
Path promoted = staging.resolveSibling("release-final.txt");
try {
Files.move(release, promoted, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException fallback) {
// 个别文件系统不支持原子移动:退回普通 move
Files.move(release, promoted, StandardCopyOption.REPLACE_EXISTING);
}
System.out.println(promoted + " -> " + Files.readAllLines(promoted));
Files.deleteIfExists(staging);
Files.deleteIfExists(promoted);
}
}How it works
Files Copy Move Atomic Replace reduces to the class StagePromotion.
The flow lives in the class StagePromotion and the function main. Files.createTempFile("deploy-", ".tmp") creates the staging file, and staging.resolveSibling("release.txt") places the first target beside it in the same directory. Files.writeString writes the build marker and checksum lines, then Files.copy with StandardCopyOption.REPLACE_EXISTING copies to release under explicit overwrite semantics. The promote step calls Files.move(release, promoted, StandardCopyOption.ATOMIC_MOVE) inside a try, and on IOException falls back to a plain Files.move with REPLACE_EXISTING for filesystems that cannot move atomically. The closing lines print promoted together with Files.readAllLines(promoted) and remove both files via Files.deleteIfExists.
Core lines
Files.move(release, promoted, StandardCopyOption.REPLACE_EXISTING);
Files.copy(staging, release, StandardCopyOption.REPLACE_EXISTING);
Files.writeString(staging, "build 2026-11-09\nchecksum ok\n");
Interactive Tools for This Topic
FAQ
- How do you run Files Copy Move Atomic Replace?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.