What is FileUtils.cleanDirectory() in Java?

cleanDirectory() is a staticthe methods in Java that can be called without creating an object of the class. method of the FileUtils class that is used to delete all the files and sub-directories in a given directory, without deleting the given directory.

How to import FileUtils

The definition of FileUtils can be found in the Apache Commons IO package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


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

For other versions of the commons-io package, refer to the Maven Repository.

You can import the FileUtils class as follows:


import org.apache.commons.io.FileUtils;

Syntax


public static void cleanDirectory(final File directory)

Parameters

  • final File directory: The directory to clean.

Return value

The method does not return anything.

Code

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
public class Main{
public static void main(String[] args){
try {
File dirFile = new File("/Users/educative/Documents/temp");
System.out.println("Number of files before calling FileUtils.cleanDirectory() method clean directory - " + dirFile.listFiles().length);
System.out.println("The files are as follows:");
Arrays.stream(Objects.requireNonNull(dirFile.listFiles())).forEach(System.out::println);
System.out.println("----");
FileUtils.cleanDirectory(dirFile);
System.out.println("Number of files after calling FileUtils.cleanDirectory() method clean directory - " + dirFile.listFiles().length);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}

In the code above, we list the contents of the directory: temp. Then, calling the cleanDirectory() method deletes the files and directories in the given directory without deleting the directory itself.

Output

The output of the code will be as follows.



Number of files before calling FileUtils.cleanDirectory() method clean directory - 10
The files are as follows:
/Users/educative/Documents/temp/1.json
/Users/educative/Documents/temp/2.json
/Users/educative/Documents/temp/5.txt
/Users/educative/Documents/temp/4.txt
/Users/educative/Documents/temp/3.txt
/Users/educative/Documents/temp/2.txt
/Users/educative/Documents/temp/1.txt
/Users/educative/Documents/temp/hello
/Users/educative/Documents/temp/3.json
/Users/educative/Documents/temp/4.json
/Users/educative/Documents/temp/5.json
----
Number of files after calling FileUtils.cleanDirectory() method clean directory - 0

Free Resources