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

前端 未结 8 2099
难免孤独
难免孤独 2020-12-09 07:55

I have a cluster of machines, each running a Java app.

These Java apps need to access a unique resource.txt file concurently.

I need to atomical

8条回答
  •  庸人自扰
    2020-12-09 08:18

    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);
    

提交回复
热议问题