gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:32:06 24 4
gpt4 key购买 nike

我们的门户网站将读取json文件来显示信息。json文件将由java编写的作业生成。

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

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

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

我的代码如下:

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

关于java - 当我的java进程重命名源文件时,任何进程都可以读取目标文件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com