How to delete directory content in Java? [duplicate]

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.


Solution 1:

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);

Solution 2:

To delete folder having files, no need of loops or recursive search. You can directly use:

FileUtils.deleteDirectory(<File object of directory>);

This function will directory delete the folder and all files in it.

Solution 3:

All files must be delete from the directory before it is deleted.

There are third party libraries that have a lot of common utilities, including ones that does that for you:

  • Apache commons-lang FileUtils.forceDelete(..)
  • guava Files.deleteRecursively(..)