In an earlier article, we looked at different ways of deleting a directory in Java. In this article, you'll learn how to delete a non-empty directory recursively — delete all its files and sub-folders.
Java provides multiple methods to delete a directory. However, the directory must be emptied before we delete it. To remove all contents of a particular directory programmatically, we need to use recursion as explained below:
- List all contents (files & sub-folders) of the directory to be deleted.
- Delete all regular files of the current directory (exist from recursion).
- For each sub-folder of the current directory, go back to step 1 (recursive step).
- Delete the directory.
Let us look at different ways to implement the above simple recursive algorithm.
Using Files.walk() Method - NIO API
In Java 8 or higher, you can use Files.walk() from NIO API (classes in java.nio.* package) to recursively delete a non-empty directory. This method returns a Stream that can be used to delete all files and sub-folders as shown below:
try {
// create a stream
Stream<Path> files = Files.walk(Paths.get("dir"));
// delete directory including files and sub-folders
files.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::deleteOnExit);
// close the stream
files.close();
} catch (IOException ex) {
ex.printStackTrace();
}
In the above example, Files.walk() returns a Stream of Path. We sorted it in the reverse order to place the paths indicating the contents of directories before directories itself. Afterward, it maps Path to File and deletes each File.
Using Java I/O Package
To delete a non-empty directory using Java legacy I/O API, we need to manually write a recursive function to implement the above algorithm. Here is how it looks like:
public void deleteDir(File dir) {
File[] files = dir.listFiles();
if(files != null) {
for (final File file : files) {
deleteDir(file);
}
}
dir.delete();
}
As you can see above, we are using File.listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File.delete().
Now you can call the above method as follows:
File dir = new File("dir");
deleteDir(dir);
Using Apache Commons IO
The Apache Commons IO library provides FileUtils.deleteDirectory() method to delete a directory recursively including all files and sub-directories:
try {
// directory path
File dir = new File("dir");
// delete directory recursively
FileUtils.deleteDirectory(dir);
} catch (IOException ex) {
ex.printStackTrace();
}
Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
For a Gradle project, add the following dependency to your build.gralde file:
implementation 'commons-io:commons-io:2.6'
Further Reading
You may be interested in other Java I/O articles:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.