How to atomically rename a file in Java, even if the dest file already exists?

For Java 1.7+, use java.nio.file.Files.move(Path source, Path target, CopyOption... options) with CopyOptions “REPLACE_EXISTING” and “ATOMIC_MOVE”.

See API documentation for more information.

For example:

Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);

Leave a Comment