当我的 java 进程重命名源文件时,任何进程都可以读取目标文件吗

can any process read the target file when my java process renaming the source file

我们的门户网站将读取 json 文件以显示信息。 json 文件将由 java.

编写的作业生成
  1. 我担心如果java进程直接写入json,网站进程可能会得到一个不完整的文件,因为java进程正在写入文件。

  2. 所以我决定把信息写到一个临时文件中,临时文件ok后,重命名为目标文件,这样网站进程就会得到完整的json文件。

  3. 但我在重命名文件时仍然担心,是否有任何进程可以读取目标文件的中间状态。实际上,我不知道 java 是如何实现重命名操作的。

我的代码如下:

Path source = FileSystems.getDefault().getPath("/data/temp/temp.7z.bak");
Files.move(source, source.resolveSibling("/data/temp/temp.7z"), StandardCopyOption.REPLACE_EXISTING);

您可能希望在方法调用中使用 ATOMIC_MOVE 选项:

Files.move(source, source.resolveSibling("/data/temp/temp.7z"), StandardCopyOption.ATOMIC_MOVE));

确实,documentation 指出

ATOMIC_MOVE

The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException. If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

这应该保证文件在没有中间状态的情况下完全移动。

请注意,如果无法进行此类原子操作,您将得到 AtomicMoveNotSupportedException