文件无法删除java.io.IOException: Unable to delete

疑问:1.为什么调用file.delete()方法时,返回值为false.

   2.为什么调用Guava工具jar包中的Files.move(from,to) ,报异常:java.io.IOException: Unable to delete

 

执行代码程序前需要创建一个test.txt文件。

 

上代码:

 

package indi.johnny.test007;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {
    
    public static void main(String[] args) {
        try {
            File file = new File("C:/Users/johnny/Desktop/test.txt");
            
            if(file.exists()){
                InputStream inputStream = new FileInputStream(file);
                //inputStream.close();
                boolean flag = file.delete();
                System.out.println(flag);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        
        
    }
    

}

 

执行以上代码会打印出 "false",也就是说删除文件失败。

但是将上述代码中的注释行"inputStream.close();"打开,则打印出"true",删除文件成功。

 

结论:通过文件加载的数据流InputStream,若未关闭,则文件无法删除。

 

Guava中的Files.move(from,to)方法有调用file.delete()方法,所以当inputStream未执行close()方法时,会报异常"Unable to delete"。

以下为Guava中Files.move(from,to)方法内容:

 

public static void move(File from, File to)
/*     */     throws IOException
/*     */   {
/* 494 */     Preconditions.checkNotNull(from);
/* 495 */     Preconditions.checkNotNull(to);
/* 496 */     Preconditions.checkArgument(!from.equals(to), "Source %s and destination %s must be different", new Object[] { from, to });
/*     */     
/*     */ 
/* 499 */     if (!from.renameTo(to)) {
/* 500 */       copy(from, to);
/* 501 */       if (!from.delete()) {
/* 502 */         if (!to.delete()) {
/* 503 */           throw new IOException("Unable to delete " + to);
/*     */         }
/* 505 */         throw new IOException("Unable to delete " + from);
/*     */       }
/*     */     }
/*     */   }

 

转载于:https://www.cnblogs.com/xxyfhjl/p/5577463.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值