CornCat
CornCat

Reputation: 304

Android Delete Directory Not Working

I am trying o delete an entire directory. I have searched and I am using this code and I am able to delete everything in the directory, but the directory still remains. Here is the exact code I have just in case I am missing something.

public boolean DeletePoint(String JobName, String PointName){
    //Delete actual contents and file
    File folder = new File(rootSaveFolder "/" + PointName+"/");
    boolean returnBool = false; 
    try{
        returnBool = deleteDirectory(folder);
        folder.delete();
    } catch (SecurityException e){
        e.printStackTrace();
    }   
}

static public 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());
  } 

The string for the file I am deleting is: /mnt/sdcard/test/gg/

I have tried it with out the final '/' and that didn't work either.

Upvotes: 2

Views: 3406

Answers (4)

swati kapoor
swati kapoor

Reputation: 131

try {
    File tempFolder = new File(path);

    for (File f : tempFolder.listFiles()){
        if (!f.isDirectory()) {
            f.delete();
        }
        tempFolder.delete();
    }

} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 0

Ethan Sherr
Ethan Sherr

Reputation: 443

Here is your problem;

Your recursion is almost right... Here's the problem.

If files[i] is a directory, (you rightfully go to clear everything in it) However, once "everything" in files[i] is deleted, you do not actually delete files[i] itself.

So the recursion is incomplete; What you need to do is remove the "else" within the forloop.

That way when files[i] which is a directory, will be cleaned up after all things in it have been removed. You were just leaving it.

To be more specific:

public void deleteFile(String uri)
{
     File currentFile = new File(uri);
     File files[] = currentFile.listFiles();
     for (int i = 0; i < files.length; i++)
     {
          if (files[i].isDirectorty())
          {
              deleteFiles(files[i].toString());
          }
          //no else, or you'll never get rid of this folder!
          files[i].delete();
     }
}

Upvotes: 3

Justin Breitfeller
Justin Breitfeller

Reputation: 13801

How are you verifying that the folder is left over? Sometimes the DDMS file explorer is out of sync and you need to refresh it before you see the directory go away.

Upvotes: 0

Rawr
Rawr

Reputation: 2224

Have you set the proper permissions - WRITE_EXTERNAL_STORAGE in your manifest. Easy to overlook sometimes :/

Look at the source topic, I think that guy got it to work...

Source: Delete a folder on SD card

Upvotes: 0

Related Questions