# How to delete a directory recursively in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 14, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-delete-directory-recursively

> A quick article to learn how to delete a directory with files and sub-directories in Java.

In an earlier article, we looked at different [ways of deleting a directory](https://attacomsian.com/blog/java-delete-directory) in Java. In this article, you'll learn how to **delete a non-empty directory recursively** &mdash; 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](https://en.wikipedia.org/wiki/Recursion) as explained below:

1. [List all contents](https://attacomsian.com/blog/java-list-all-files-in-a-directory) (files & sub-folders) of the directory to be deleted.
2. Delete all regular files of the current directory (exist from recursion).
3. For each sub-folder of the current directory, go back to step 1 (recursive step).
4. 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:

```java
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:

```java
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](https://attacomsian.com/blog/java-list-all-files-in-a-directory#using-filelistfiles-method) 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:

```java
File dir = new File("dir");
deleteDir(dir);
```

## Using Apache Commons IO

The [Apache Commons IO](https://commons.apache.org/proper/commons-io/) library provides `FileUtils.deleteDirectory()` method to delete a directory recursively including all files and sub-directories:

```java
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:

```xml
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
```

For a [Gradle project](https://attacomsian.com/blog/install-gradle-on-ubuntu), add the following dependency to your `build.gralde` file:

```groovy
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](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
