How to delete a folder and all its sub folders and contents using Recursion?
A folder can be deleted with a simple command in java programming.
File.delete();
But sometimes, When a folder contains files or sub folders, this method does not work. Join me if you want to know how this problem can be sorted effectivley.
Introduction
Can't seem to delete a folder which has contents using delete() method?
Whats the possible solution for this annoying problem. Well, It is a simple concept, that a folder cannot be deleted until all its contents are deleted.
Note: A file will not be deleted if it is open. So just make sure, the inputstream is closed before deletion.
Algorithm
The simple algorithm for using recursion in this problem is:
1. If folder:
- list its contents
- for each content
- repeat 1
2. else If File
- delete file
This procedure will be iterated until every file/folder is deleted & finally will reach the root folder and at that point, the root folder will be empty which eventually will also be deleted.
Solution
Here, a recursive procedure is described to delete any complicated or simple folder structure.
* Reursive/ self calling method
*/
public static void delete(File folder)
{
if(folder.exists())
{
File[] files = folder.listFiles();
for(int nFileCur=0; nFileCur < files .length; nFileCur++)
{
File oFileCur = files [nFileCur];
if(oFileCur.isDirectory())
{
// call itself to delete the contents of the current folder
delete(oFileCur);
}
oFileCur.delete();
}
}
}
Tips
Make the method Static because it is generic calculation, so the functionality can be used from outside the class it is defined in.
This method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and if it wasn't declared static, it would have to be qualified with an object unnecessarily.








Comments
so what happens? it deletes a folder called File folder?
so what happens? it deletes a folder called File folder?
well.. since that is a
well.. since that is a function, it deletes any folder with a datatype File.. Everytime you call that function, you have to pass a File
Post new comment