How to delete directory content in Java?

lola picture lola · Oct 14, 2011 · Viewed 141.6k times · Source

After enumerating a directory, I now need to delete all the files.

I used:

final File[] files = outputFolder.listFiles();
files.delete();

But this hasn't deleted the directory.

Answer

NCode picture NCode · Oct 14, 2011

You have to do this for each File:

public static void deleteFolder(File folder) {
    File[] files = folder.listFiles();
    if(files!=null) { //some JVMs return null for empty dirs
        for(File f: files) {
            if(f.isDirectory()) {
                deleteFolder(f);
            } else {
                f.delete();
            }
        }
    }
    folder.delete();
}

Then call

deleteFolder(outputFolder);