Search code examples
javaandroidfile-io

How to delete all files and folders in one folder on Android


I use this code to delete all files:

File root = new File("root path");
File[] Files = root.listFiles();
if(Files != null) {
    int j;
    for(j = 0; j < Files.length; j++) {
        System.out.println(Files[j].getAbsolutePath());
        System.out.println(Files[j].delete());
    }
}

It will delete false where Files[j] is a folder.

I want to delete folder and all its sub files.
How can I modify this?


Solution

  • Simplest way would be to use FileUtils.deleteDirectory from the Apache Commons IO library.

    File dir = new File("root path");
    FileUtils.deleteDirectory(dir);
    

    Bear in mind this will also delete the containing directory.

    Add this line in gradle file to have Apache

    compile 'org.apache.commons:commons-io:1.3.2'