Java: How to delete a directory tree

Java directory FAQ: “How do I delete a directory tree in Java?”

Solution

The delete method of the File class won’t delete a directory tree, which meant that in the old days you had to write your own recursive method to do this.

But fortunately today you can just use a static method in the FileUtils class of the Jakarta Commons IO project, like this:

FileUtils.delete("/Users/al/old-directory");

As you might guess, this deletes the directory named old-directory in my home directory (/Users/al).

Just download the Commons IO library and include it in your project, and you’re ready to go.

A Java delete directory method

I just ran across a Java method I created as a wrapper around the code shown above, so I thought I’d share it here as well. First, here are the necessary import statements that go at the top of the class:

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;

Next, here's my Java "delete directory" wrapper method:

public void deleteDirectory(String directoryName)
throws IOException
{
  try
  {
    FileUtils.deleteDirectory(new File(directoryName));
  }
  catch (IOException ioe)
  {
    // log the exception here
    ioe.printStackTrace();
    throw ioe;
  }
}

As you can see, this is just a simple wrapper class that lets you log any potential IOException before you re-throw it.