Home » Android » android – Delete a folder on SD card

android – Delete a folder on SD card

Posted by: admin April 23, 2020 Leave a comment

Questions:

I tried File.delete() but it doesn’t work. How to delete a directory on SD card?

I’m working on Android 2.1.

How to&Answers:

You have to have all the directory empty before deleting the directory itself, see here

In Android, you should have the proper permissions as well – WRITE_EXTERNAL_STORAGE in your manifest.

EDIT: for convenience I copied the code here, but it is still from the link above

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

Answer:

https://stackoverflow.com/a/16411911/2397275

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in AndroidManifest.xml file

Answer:

Directories must be empty before they will be deleted. You have to recursively empty and delete all directories in the tree:

boolean delete(File file) {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null)
            for (File f : files) delete(f);
    }
    return file.delete();
}

Update:

It seems like file.isDirectory() == (file.listFiles() == null), but file.listFiles() logs “fail readDirectory() errno=20” when file.isDirectory() == false.

Answer:

it’s worked fine for me, i hope it will work for you.

File dir = new File(Environment.getExternalStorageDirectory()+"DirName"); 
if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            new File(dir, children[i]).delete();
        }
    }

Answer:

It worked for me:

Add in manifest-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

private boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            if (files == null) {
                return false;
            }
            for(File file : files) {
                if(file.isDirectory()) {
                    deleteDirectory(file);
                }
                else {
                file.delete();
                }
            }
        }
        return path.exists()?path.delete():false;
    }