2012-07-24 115 views
1

在我jUnit,我有一個下面的代碼片段:無法刪除目錄,爪哇

private String session = "/tmp/session/"; 
private File f; 

@Before 
public void setUp() { 
    f = new File(session); 
    f.mkdir(); 
} 

@After 
public void tearDown() { 
    System.out.println("Directory deleted: " + f.delete()); // always false 
} 

同時:

  • Directory權限都OK(drwxr-xr-x
  • 目錄包含一些文件(-rw-r--r--
  • 沒有所有權問題(創建者用戶刪除)

f.delete()會失敗的原因是什麼?是f.delete()相當於rm -rf

+2

是目錄空目錄? – 2012-07-24 16:54:41

+0

@PaulTomblin號更新的問題 – JAM 2012-07-24 16:55:12

回答

3

從File.delete的API文檔:

delete 

public boolean delete() 
Deletes the file or directory denoted by this abstract pathname. If this pathname 
denotes a directory, then the directory must be empty in order to be deleted. 
Returns: 
true if and only if the file or directory is successfully deleted; false otherwise 
Throws: 
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete 

訪問文件

注意有關該目錄需要是空位。

+0

嘆氣..應該是空的..完全錯過了這一點。將遍歷並刪除單個文件。謝謝保羅 – JAM 2012-07-24 16:57:30

+0

@Jam不要重新發明輪子。如[Óscar建議]使用庫(http://stackoverflow.com/a/11635778/139010)。 – 2012-07-24 17:35:43

+0

@MattBall更棒!謝謝 – JAM 2012-07-24 18:20:20

3

如前所述,在刪除它之前,您的目錄需要爲空。有一個偉大的教程here,你應該看看。您需要目錄及其所有文件的recursive delete,因爲該目錄在刪除之前需要爲空。

6

遞歸刪除一個非空目錄(而不是重塑過程中的車輪)的最簡單的方法是從現有的庫使用的功能,說阿帕奇百科全書文件utils的的FileUtils.deleteQuietly()方法,該方法規定:

如果文件是一個目錄,刪除它和所有子目錄(...)將被刪除並不一定是空的

+1

當然,在決定使用現有的庫時,應該考慮它可能對WAR文件的大小,啓動時間和許可有什麼影響,但Apache Commons通常很好,很小,速度快,並且使用相當的許可證。 – 2012-07-24 18:36:49