Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.6. Deleting Directories Recursively

10.6.1. Problem

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

10.6.2. 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.

10.6.3. 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" );
}

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.