简体   繁体   English

无法删除目录,Java

[英]Trouble deleting directory, Java

In my jUnit , i have a following snippet: 在我的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
}

Meanwhile: 与此同时:

  • Directory permissions are ok ( drwxr-xr-x ) 目录权限还可以( drwxr-xr-x
  • Directory contains some files ( -rw-r--r-- ) 目录包含一些文件( -rw-r--r--
  • No ownership issues (Creator user deletes) 没有所有权问题(创建者用户删除)

What would cause for f.delete() to fail? 什么会导致f.delete()失败? Is f.delete() an equivalent of rm -rf ? f.delete()是否等于rm -rf

The simplest way to recursively delete a non-empty directory (and not reinvent the wheel in the process) is to use functionality from an existing library, say the FileUtils.deleteQuietly() method of Apache Commons' file utils which specifies that: 递归删除非空目录(而不是浪费时间)的最简单方法是使用现有库中的功能,例如Apache Commons文件utils的FileUtils.deleteQuietly()方法,该方法指定:

If file is a directory, delete it and all sub-directories (...) A directory to be deleted does not have to be empty 如果文件是目录,请删除该文件及其所有子目录(...)要删除的目录不必为空

From the API documentation for File.delete: 从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 

access to the file 访问文件

Note the bit about the directory needing to be empty. 注意有关目录的位需要为空。

As said before, your directory needs to be empty before you delete it. 如前所述,您的目录在删除之前需要为空。 There is a great tutorial here that you should take a look at. 有一个伟大的教程在这里 ,你应该看一看。 You need to a recursive delete of the directory and all of its files, because the directory needs to be empty before you delete it. 您需要recursive delete目录及其所有文件,因为在删除目录之前,该目录必须为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM