Sample Application: Delete Directory
This function implements how to delete a directory along with all its contents. The function takes each content one by one and deleting it.
This is an example of a recursive function. A recursive function means, a function which references itself. In other words, it is a method of defining functions in which the function being defined is applied within its own definition.
// -----------------------------------------------------------------------------
// DeleteDirectory.java
// -----------------------------------------------------------------------------
import java.io.File;
public class DeleteDirectory {
/**
* -----------------------------------------------------------------------
* This function deletes a directory along with its contents recursively
*
* File dir_name matches the directory to be deleted
* File Array files hold the list of files and subdirectories
*
* @param dir mapping the directory
* @return boolean value
*
* -----------------------------------------------------------------------
**/
public static boolean deleteDirectory(String dir) {
try {
File dir_name = new File(dir);
//Checks if the directory exists
if(dir_name.exists()) {
File[] files = dir_name.listFiles();
//Delete files and subdirectories recursively
for(int i=0; i<files.length; i++) {
//Checks whether the child file is directory,
//if yes call main function recursively,
// else delete the file
if(files[i].isDirectory()) {
deleteDirectory(files[i].getName());
}
else {
files[i].delete();
}
}
}
//return the value of directory deletion
return( dir_name.delete() );
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
}
DeleteDirectory.java deletes a directory along with all its contents irrespective of whether the content is a directory or a file.