How to delete a whole folder and content?


Question

I want the users of my application to be able to delete the DCIM folder (which is located on the SD card and contains subfolders).

Is this possible, if so how?

1
162
8/17/2014 2:32:13 PM

Accepted Answer

Let me tell you first thing you cannot delete the DCIM folder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the DCIM folder. You can delete its contents by using the method below:

Updated as per comments

File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {
       new File(dir, children[i]).delete();
    }
}
280
8/7/2015 1:21:56 PM

You can delete files and folders recursively like this:

void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
            deleteRecursive(child);

    fileOrDirectory.delete();
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon