Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a folder on SD card

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

I'm working on Android 2.1.

like image 684
Greenhorn Avatar asked Apr 18 '11 10:04

Greenhorn


People also ask

Why can't I delete folders from my SD card?

▶ The file system of SD card partition is corrupted. If so, your SD card might be protected by adding read-only attributes to all files. Thus, you are not allowed to delete files.

Can I delete Android folder in SD card?

If it's stored in the SD card, you can perform the deletion on Android device or computer easily. While it's stored in Android memory, just delete it on Android.

Why can't I delete files from Micro SD card?

Cause 2: Read-only mode. There might be a "Lock" tab present. If the tab is switched on, then it will successfully lock your storage device and will enable a read-only mode. Now files cannot be deleted from the SD card.


3 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() );
  }
like image 69
MByD Avatar answered Oct 23 '22 06:10

MByD


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

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

in AndroidManifest.xml file

like image 34
Codeerror Avatar answered Oct 23 '22 05:10

Codeerror


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();
        }
    }
like image 1
Murali Mohan Avatar answered Oct 23 '22 04:10

Murali Mohan