java files.move_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;

}

}

这是我收到bFvbe.png的例外情况

在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值