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" );
}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access