I am trying to remove a directory recursively. But I've got some problems. So, I create in my "test" folder some directories as it shown on the picture. But in in 3rd folder it throws an exception java.lang.NullPointerException.
Here's the picture and some code:
public static void RecursiveRm (String myFile)
{
File fl = new File(myFile);
String [] temp = fl.list();
if(temp.length > 0){
for (int i = 0; i < temp.length; ++i){
myFile = myFile + "/" + temp[i];
RecursiveRm(myFile);
}
}
else
fl.delete();
}
That's how it works
You shouldn't be doing this for a start.
myFile = myFile + "/" + temp[i];
This means that if you have a directory with a
b
and c
in it the path will become /a/b/c
You should avoid changing myFile
Try this instead.
for(String file: new File(myFile).list()) {
recursiveRm(myFile + "/" + file);
}
fl.delete();
Most likely you are getting a NullPointerException as File.list()
return null
if the directory doesn't exist.