Friday, March 20, 2009

Java code to delete entire folder structure with files in it

Ever tried file.delete() and wondered why your non empty directory is not deleted? Irony with java's api is that it returns a boolean when we expect it to either delete or fail! Here is a simple recursive function that will do the trick of deleting any file or folder with or without nested structure.

If you use this method in your application, do so at your own risk. I have not tested it for boundary conditions...
public static void deleteResource(File file){
if (file != null)
if (file.isFile())
file.delete();
else if (file.isDirectory()){
File[] resources = file.listFiles();
if (resources.length == 0)
file.delete();
else {
for (File resource: resources)
deleteResource(resource);
deleteResource(file);
}
}
}

Labels: , , , , ,

0 Comments:

Post a Comment

<< Home