我想删除一个文件并将另一个文件重命名为旧文件,但是我无法移动此文件,因为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异常。
我还编辑了之前的问题,因为它没有清楚说明。
请帮忙解决。
Anuj