user1796624
user1796624

Reputation: 4007

how to delete the contents in getExternalFilesDir(null) android

I have saved some files by using the command:

File file = new File(cont.getExternalFilesDir(null), filename);

how can I delete all of the files I have saved? I need to clear the content of cont.getExternalFilesDir(null) directory. Thanks

Upvotes: 3

Views: 2298

Answers (3)

Moisoni Ioan
Moisoni Ioan

Reputation: 1425

You can delete delete any Dir with this:

private static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        if (children != null) {
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    } else if (dir != null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

Then just call:

 try {
        File dir = this.getExternalFilesDir("yourdirname");
        deleteDir(dir);
    } catch (Exception e) {
        e.printStackTrace();
    }

Upvotes: 0

GhostDerfel
GhostDerfel

Reputation: 1551

If you want to delete just a file you can do as told by Perroloco, but if you need do delete all content I think a OO approach will be better :)

First just build a method to delete files inside a directory recursively

private void deleteAllContent(File file,String... filename) {
    if (file.isDirectory())
        for (File child : file.listFiles())
            deleteAllContent(child);
    if(filename==null)
        file.delete();
    else
        for(String fn:filename)
            if(file.getName().equals(filename))
                file.delete(); 
}

Then you can just call your new method with your external files dir.

deleteAllContent(cont.getExternalFilesDir(null));

or

deleteAllContent(cont.getExternalFilesDir(null),"myfile1","myfile2","etc");

Upvotes: 4

Sebastian Breit
Sebastian Breit

Reputation: 6159

File file = new File(cont.getExternalFilesDir(null), filename);
file.delete();

Upvotes: 2

Related Questions