Reputation: 3804
I am having trouble deleting folders.
I made folders and folders.delete returns false. Why?
I also tried this below. This returns false and the folder doesn't get erased. Why?
public static boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}
Upvotes: 0
Views: 4718
Reputation: 5659
Inspired by this solution:
Android Delete Directory Not Working
I have improved it as follows, and it worked for me:
private void deleteSubFolders(String uri)
{
File currentFolder = new File(uri);
File files[] = currentFolder.listFiles();
if (files == null) {
return;
}
for (File f : files)
{
if (f.isDirectory())
{
deleteSubFolders(f.toString());
}
//no else, or you'll never get rid of this folder!
f.delete();
}
}
Notes: be mindful of the folder name being passed around. For example:
File folder = new File("path/to/directory");
folder.getName() is not necessarily equal to the full path directory name.
Upvotes: 4