【发布时间】:2017-02-13 06:24:50
【问题描述】:
这段代码:
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 [警告] [_Executor-1] a.b.c.MyGenerator - 文件夹中已存在文件“myFile_01092016103511.csv” '/myDir': 在生成时间上增加一秒
2016-10-04 10:35:11,677 [警告] [_Executor-3] a.b.c.MyGenerator - 文件夹中已存在文件“myFile_01092016103511.csv” '/myDir': 在生成时间上增加一秒
2016-10-04 10:35:11,677 [INFO] [_Executor-1] a.b.c.MyGenerator - The 临时文件“tmp2103892505851032137.tmp”重命名为 'myFile_01092016103512.csv'
2016-10-04 10:35:11,680 [INFO] [_Executor-3] a.b.c.MyGenerator - 临时文件“tmp6843688962754506611.tmp”重命名为 'myFile_01092016103512.csv'
Executor 3 覆盖文件,即使它应该抛出 FileAlreadyExistsException。
没有抛出异常,文件的数据已经被覆盖。
【问题讨论】:
标签: java multithreading file io