0

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() );
          }
coolcool1994
  • 3,704
  • 4
  • 39
  • 43
  • Do you have the required permissions? – poitroae Feb 03 '13 at 15:55
  • Yes, I do. I am saving and deleting in the internal storage ( ) – coolcool1994 Feb 03 '13 at 15:56
  • http://developer.android.com/reference/android/Manifest.permission.html the permission android.permission.WRITE_INTERNAL_STORAGE dows NOT exist! – StarsSky Feb 03 '13 at 16:00
  • Well, I don't think you even need a permission to write in internal storage. I actually published my previous app with this permission and it saved fine in the internal storage, but this permission did not come up in the googlePlay. I doubt that now you even need a permission to write in the internal storage. StarsSky - what permission then are you suggesting? – coolcool1994 Feb 03 '13 at 16:02

1 Answers1

4

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.

Community
  • 1
  • 1
Phileo99
  • 5,581
  • 2
  • 46
  • 54