Java - How to delete a directory tree

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

Java delete directory - discussion

The delete method of the File class won't delete a directory tree, meaning 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:


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:


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

public void deleteDirectory(String directoryName)
throws IOException
    FileUtils.deleteDirectory(new File(directoryName));
  catch (IOException ioe)
    // log the exception here
    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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.