10.6. Deleting Directories Recursively

Problem

You need to delete a directory and everything it contains. You need a recursive delete—the equivalent of a Unix rm -r.

Solution

Use FileUtils.deleteDirectory() to remove a directory and everything below it. The following example deletes the temp directory:

import org.apache.commons.io.FileUtils;

try {
    File dir = new File( "temp" );
    FileUtils.deleteDirectory( dir );
} catch( IOException ioe ) {
    System.out.println( "Error deleting directory." );
}

This code will delete every file and directory in the temp directory and, once the directory is empty, deleteDirectory( ) will remove the temp directory itself.

Discussion

You can also “clean” a directory with the cleanDirectory() method. When cleaning a directory, the contents of the directory are erased, but the directory itself is not deleted. The following example cleans the temp directory, emptying it of all files and subdirectories:

import org.apache.commons.io.FileUtils;

try {
    File dir = new File( "temp" );
    FileUtils.cleanDirectory( dir );
} catch( IOException ioe ) {
    System.out.println( "Problem cleaning a directory" );
}

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.