文件无法删除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