You need to delete a directory and everything it contains. You need a recursive delete—the
equivalent of a Unix rm -r.
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.
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" );
}