Java Delete All Files and Directories Inside a Directory using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File

In this Java tutorial we show you how to use the FileUtils class of Apache Commons IO library to delete all files and directories in a given directory.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Clean a Directory

For example we have the directory D:\TestData, in the following Java program we use the FileUtils.cleanDirectory() method to clean the given directory without deleting itself.

CleanDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CleanDirectory {
    public static void main(String... args) {
        try {
            File directoryToClean = new File("D:\\TestData");

            FileUtils.cleanDirectory(directoryToClean);
            System.out.println("Clean directory " + directoryToClean + " success!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Clean directory D:\TestData success!

Happy Coding 😊