编程语言
首页 > 编程语言> > Files.move和Files.copy抛出了java.nio.file.FileAlreadyExistsException

Files.move和Files.copy抛出了java.nio.file.FileAlreadyExistsException

作者:互联网

我想删除一个文件并使用旧文件重命名另一个文件,但我无法移动此文件,因为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;
        }
    }

这是我收到enter image description here的例外情况
在Files.move上(tempPath,tempPath.resolveSibling(origFileName),StandardCopyOption.REPLACE_EXISTING);

此外,当我在Windows资源管理器中看到此文件时,其缩略图存在但无法打开它.我无法理解它为什么会发生,如果我使用REPLACE_EXISTING,为什么它会抛出FileAlreadyExistsException异常.

我也编辑了上一个问题,因为它没有明确说明.

请帮忙.

Anuj

解决方法:

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

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

ATOMIC_MOVE : The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException. If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

标签:java,java-nio-file
来源: https://codeday.me/bug/20190527/1166607.html