2012-07-24 119 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