This post will discuss how to recursively delete a directory in Java.

There are several ways to delete a directory and all its subdirectories in Java and using third-party libraries such as Apache Commons IO and Guava. These are discussed below in detail:

1. Using Apache Commons IO

Apache Commons IO’s FileUtils class provides several utility methods for working with files. To delete a directory recursively, we can use its deleteDirectory(File directory) method. It takes a directory to delete and throws an IOException if the deletion is unsuccessful.

If the specified directory contains a symbolic link (on Unix/Linux machines), it deletes the link itself but won’t follow the link and deletes all the files the link points to.

Download Code

 
To avoid catching an exception, the deleteQuietly(File directory) method can quietly delete a directory and all its subdirectories.

We can also use forceDelete(File file) method of the FileUtils class. It works similarly to the FileUtils::deleteDirectory method.

2. Using Guava Library

With Guava 21.0, we can use the MoreFiles class, which provides several static utilities for Path instances. We can use the deleteRecursively(Path path) method to deletes the directory at the given path recursively. With symbolic links, the link is deleted and not the target of the link.

Download Code

3. Using Files Class

With Java 7, Files.delete(Path path) method can be used with the java.nio.file.Files.walkFileTree(…) method to delete a directory and all entries in it. The following example demonstrates the usage of these methods to delete a directory:

Download Code

4. Using Java 8

With Java 8, we can use the java.nio.file.Files.walk(…) method that returns a Stream of Path objects by walking the file tree in a depth-first manner is rooted at a given starting file.

The following code shows how to use the Files.walk(…) method with the File.delete() method to recursively delete the specified directory and all its subdirectories. Since the file tree is traversed depth-first manner and File::delete won’t allow deleting a non-empty directory, we have used a reverse order comparator to ensure the parent directory is deleted after the child.

Download Code

5. Java 6

In Java 6 and before, we can write a custom routine to delete a directory recursively. Here’s a working example:

Download Code

6. Using Runtime Class

Every Java application has a single instance of the Runtime class, and we can obtain the current runtime from the getRuntime() method. We can use the Runtime.exec(command) convenience method to execute the corresponding remove directory command of the underlying environment.

Download Code

That’s all about deleting a directory in Java.

 
Also See:

Move a directory in Java

Copy a directory in Java