Delete folder in Java using recursion

August 18, 2020 No comments Java IO Folder Recursion Delete

1. Introduction

In this article, we are going to cover methods to remove directory recursively in Java. We will present solutions in plain Java and methods using external libraries dedicated to IO operations.

2. Delete the folder using java.io API

Let's start with an example in plain Java using 'old' java.io API.

We used a simple structure of files and folders presented by the following tree:

├── first
│   ├── file
│   └── second
│       └── third
│           ├── one.txt
│           ├── three.txt
│           └── two.txt

The java.io package provides the File.delete(...) method to remove a folder, however it works only on empty directories. To remove not-empty folders we need to remove all the files and subfolders first. This is why we need the recursion, as it is the only way to navigate through tree structures.

package com.frontbackend.java.io.remove;

import java.io.File;

public class RemoveDirectoryRecursively {

    public static void main(String[] args) {
        deleteDirectory(new File("/tmp/first"));
    }

    private static void deleteDirectory(File dir) {
        File[] resources = dir.listFiles();
        if (resources != null) {
            for (File file : resources) {
                deleteDirectory(file);
            }
        }

        dir.delete();
    }
}

In this example, we can distinguish the deleteDirectory(...) method that is called recursively.

The scenario can be described in a few steps:

1. We list all resources that should be deleted from the `root` folder,
2. Next, we delete all files from a given folder,
3. For all subfolders, we go to step 1, and in this case, our `root` will be our child,
4. Delete directory that in this step will be empty.

3. Remove folder using FileUtils from Apache Commons IO library

Apache Commons IO library comes with many great utility classes for file and folders manipulations.

Let's check the example code to delete recursively folder /tmp/first:

package com.frontbackend.java.io.remove;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class RemoveDirectoryUsingFileUtils {

    public static void main(String[] args) throws IOException {
        FileUtils.deleteDirectory(new File("/tmp/first"));
    }
}

As you can see here we have truly single-line solution that clears folder and subfolders for us.

The latest version of the Apache Commons IO dependency can be found here.

4. Delete folder using java.nio API

From JDK 8 we have Files.walk(...) method dedicated for navigation over filesystem tree structure. It returns Stream that could be easily sorted and mapped to any object we need.

package com.frontbackend.java.io.remove;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;

public class RemoveDirectoryUsingFilesWalk {

    public static void main(String[] args) throws IOException {
        Path toDelete = Paths.get("/tmp/first");

        Files.walk(toDelete)
             .sorted(Comparator.reverseOrder())
             .map(Path::toFile)
             .forEach(File::delete);
    }
}

In this example first, we sorted the result Stream to place files before directories. Then, we map the Path object to simply File. Finally, for each element, we run the delete method.

5. Conclusion

In this article, we presented different ways to delete folders recursively in Java. We saw that sometimes for better readability we could use third-party libraries such as Apache Commons IO to get a nice single-line solution. Under the hood all methods used recursion function.

The source codes for this article are available over on GitHub.

{{ message }}

{{ 'Comments are closed.' | trans }}