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:
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.
In this example, we can distinguish the deleteDirectory(...)
method that is called recursively.
The scenario can be described in a few steps:
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
:
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.
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}