This snippet show how to recursively delete directories.
This is a classic example of use of recursion to figure out files in sub folders and so on..
<!--break-->
package com.livrona.snippets.io;
import java.io.File;
/**
* This snippet show how to recursively delete directories
*
* @author java4learners
*
*/
publicclass RecursiveDirectoryDelete {
/**
* Overloaded with String path input
*
* @param dirPath
* @return
*/
publicstaticboolean deleteDirectory(String dirPath) {
// convert to file handler
File path =new File(dirPath);
return deleteDirectory(path);
}
/**
* This function will recursively delete directories and files.
*
* @param path
* File or Directory to be deleted
* @return true indicates success.
*/
publicstaticboolean deleteDirectory(File path) {
// check if path exists
if (path.exists()) {
// is directory
if (path.isDirectory()) {
// get list of file in directory
File[] files = path.listFiles();
for (int i =0; i < files.length; i++) {
// if it a directory make recursive call
// to deleteFile method
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
// delete actual file
files[i].delete();
}
}
}
}
// finally delete the path
return (path.delete());
}
publicstaticvoid main(String[] args) {
if (args.length !=1) {
System.out
.println("Usage: java com.livrona.snippets.io.RecursiveDirectoryDelete ");
System.exit(0);
}
String dirToDelete = args[0];
System.out.println("Dir : "+ dirToDelete);
boolean success = deleteDirectory(dirToDelete);
System.out.println("Dir deleted sucess : "+ success);
}
}