Delete a folder and its contents in Java
You can use the following method to delete a folder and all of its contents in Java:
/**
* Deletes the given folder and all of it contents if and only if the folder
* exists.
*
* @param folder
* The folder to be deleted
*/
public static void deleteFolderAndContents(final File folder) {
if (folder.exists()) {
final File[] files = folder.listFiles();
if (files != null) { // Some JVMs return null for empty directories
for (final File file : files) {
if (file.isDirectory()) {
deleteFolderAndContents(file);
} else {
file.delete();
}
}
}
folder.delete();
}
}