Delete a folder on SD card

Deadly 提交于 2019-11-26 09:34:54

问题


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

I\'m working on Android 2.1.


回答1:


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



回答2:


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

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

in AndroidManifest.xml file




回答3:


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.




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/5701586/delete-a-folder-on-sd-card

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!