简体   繁体   中英

Trouble deleting directory, Java

In my jUnit , i have a following snippet:

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 )
  • Directory contains some files ( -rw-r--r-- )
  • No ownership issues (Creator user deletes)

What would cause for f.delete() to fail? Is f.delete() an equivalent of 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:

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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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