gpt4 book ai didi

java - 未抛出 FileAlreadyExistsException 并覆盖文件

转载 作者:行者123 更新时间:2023-11-30 10:38:08 26 4
gpt4 key购买 nike

这段代码:

File tmpFile = File.createTempFile(PREFIX_TMP, null, new File(reportPath));
logger.debug("The report will be saved in the temporary file '{}'", tmpFile.getName());

reportWriter.write(tmpFile, report);

Calendar calendar = Calendar.getInstance();

boolean isFileMoved = false;
while (!isFileMoved) {
String reportName = String.format(report.getName(), calendar.getTime());
File reportFile = new File(reportPath, reportName);

try {
Files.move(tmpFile.toPath(), reportFile.toPath());
isFileMoved = true;

logger.info("The temporary file '{}' is renamed to '{}'", tmpFile.getName(), reportFile.getName());
} catch (FileAlreadyExistsException e) {
logger.warn("The file '{}' already exists in the folder '{}': adding a second to generation time",
reportName, reportPath);
}

calendar.add(Calendar.SECOND, 1);
}

生成以下不可能的日志语句:

2016-10-04 10:35:11,674 [WARN ] [_Executor-1] a.b.c.MyGenerator - The file 'myFile_01092016103511.csv' already exists in the folder '/myDir': adding a second to generation time

2016-10-04 10:35:11,677 [WARN ] [_Executor-3] a.b.c.MyGenerator - The file 'myFile_01092016103511.csv' already exists in the folder '/myDir': adding a second to generation time

2016-10-04 10:35:11,677 [INFO ] [_Executor-1] a.b.c.MyGenerator - The temporary file 'tmp2103892505851032137.tmp' is renamed to 'myFile_01092016103512.csv'

2016-10-04 10:35:11,680 [INFO ] [_Executor-3] a.b.c.MyGenerator - The temporary file 'tmp6843688962754506611.tmp' is renamed to 'myFile_01092016103512.csv'

Executor 3 覆盖文件,即使它应该抛出 FileAlreadyExistsException。

没有抛出异常,文件的数据已被覆盖。

最佳答案

Executor 3 overwrites the file, even though it should throw a FileAlreadyExistsException.

您需要使用 ATOMIC_MOVE option如果您希望 Files.move(...) 以原子方式执行。默认情况下,它首先测试目标是否存在,然后执行易受 thread race conditions 影响的移动。 .这是 javadocs for Files.move(...) :

ATOMIC_MOVE – Performs the move as an atomic file operation. If the file system does not support an atomic move, an exception is thrown. With an ATOMIC_MOVE you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file.

如果您必须有 FileAlreadyExistsException 支持,那么您将需要使用 synchronized block 来保护移动,以便一次只允许一个线程运行它。如果您在此 block 中执行 IO,synchronized 应该几乎没有性能损失。

关于java - 未抛出 FileAlreadyExistsException 并覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863271/

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