What is FileUtils.deleteDirectory() in Java?
Overview
deleteDirectory() is a FileUtils class that is used to delete a directory recursively.
This method deletes the contents of the directory along with the directory itself.
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-iopackage, refer to the Maven Repository.
You can import the FileUtils class as follows:
import org.apache.commons.io.FileUtils;
Syntax
public static void deleteDirectory(final File directory)
Parameters
final File directory: This is the directory to delete.
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);FileUtils.deleteDirectory(dirFile);System.out.printf("Existence of the %s directory - %s", dirFile.getName(), dirFile.exists());} catch (IOException ioException) {ioException.printStackTrace();}}}
Explanation
In the above code, we list the contents of the directory temp. We then call the method deleteDirectory(), which recursively deletes the files and directories in the given directory, before finally deleting the given directory.
We check if the directory to be deleted is still present with the help of the exists() method of the File class.
Output
The output of the code is as follows:
Number of files before calling FileUtils.cleanDirectory() method clean directory - 11
The files are as follows:
/Users/educative/Documents/temp/temp-2
/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/3.json
/Users/educative/Documents/temp/4.json
/Users/educative/Documents/temp/5.json
Existence of the temp directory - false