疑問: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); /* */ } /* */ } /* */ }