我想删除一个文件并用旧文件重命名另一个文件,但我无法移动这个文件,因为 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 异常。
我还编辑了上一个问题,因为它没有明确说明。
请帮忙。
阿努伊