我想删除一个文件并用旧文件重命名另一个文件,但由于Java抛出java.nio.file.FileAlreadyExistsException
,因此我无法移动该文件,以下是我正在使用的代码段
static void swapData(String origFilePath, String tempFilePath) throws IOException{
Path tempPath = FileSystems.getDefault().getPath(tempFilePath);
Path origPath = FileSystems.getDefault().getPath(origFilePath);
try{
String origFileName = null;
File origFileRef = new File(origFilePath);
if(Files.exists(origPath)){
origFileName = origFileRef.getName();
Files.delete(origPath);
if(Files.exists(origPath))
throw new IOException("cannot able to delete original file");
}
if(origFileName != null)
Files.move(tempPath, tempPath.resolveSibling(origFileName), StandardCopyOption.REPLACE_EXISTING);
}catch(IOException e){
throw e;
}
}
这是我收到
在
Files.move(tempPath, tempPath.resolveSibling(origFileName), StandardCopyOption.REPLACE_EXISTING);
上另外,当我在Windows资源管理器中看到此文件时,便会显示其缩略图,但无法将其打开。我不明白为什么会这样,如果我使用REPLACE_EXISTING,为什么会抛出FileAlreadyExistsException异常。
我也编辑了前面的问题,因为它没有明确说明。
请帮忙。
阿努吉
最佳答案
运行Files.move
或Files.copy
时,检查是否有另一个线程保持相同的文件资源。我有相同的异常和文件访问症状,并且可以在序列化文件访问后解决它。
另外,通过在执行REPLACE_EXISTING
或Files.copy
时使用Files.move
选项,尽管Files.move
或Files.copy
不能保证是原子的,但您不再需要编写删除原始文件然后重命名tmp的多个步骤。有一个ATOMIC_MOVE
选项,但是我不喜欢特定于实现的保证,如果文件已经存在(如javadoc所描述的那样),则可能会抛出IOException
。