我想删除一个文件并用旧文件重命名另一个文件,但由于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;
        }
    }

这是我收到java - Files.move和Files.copy抛出java.nio.file.FileAlreadyExistsException-LMLPHP的异常(exception)
Files.move(tempPath, tempPath.resolveSibling(origFileName), StandardCopyOption.REPLACE_EXISTING);

另外,当我在Windows资源管理器中看到此文件时,便会显示其缩略图,但无法将其打开。我不明白为什么会这样,如果我使用REPLACE_EXISTING,为什么会抛出FileAlreadyExistsException异常。

我也编辑了前面的问题,因为它没有明确说明。

请帮忙。

阿努吉

最佳答案

运行Files.moveFiles.copy时,检查是否有另一个线程保持相同的文件资源。我有相同的异常和文件访问症状,并且可以在序列化文件访问后解决它。

另外,通过在执行REPLACE_EXISTINGFiles.copy时使用Files.move选项,尽管Files.moveFiles.copy不能保证是原子的,但您不再需要编写删除原始文件然后重命名tmp的多个步骤。有一个ATOMIC_MOVE选项,但是我不喜欢特定于实现的保证,如果文件已经存在(如javadoc所描述的那样),则可能会抛出IOException

10-06 16:17
查看更多