Is there a way to delete entire directories recursively in Java?
In the normal case it is possible to delete an empty directory. However when it comes to deleting entire directories with contents, it is not that simple anymore.
How do you delete entire directories with contents in Java?
If you have Spring, you can use FileSystemUtils.deleteRecursively:
An optimal solution that handles exception consistently with the approach that an exception thrown from a method should always describe what that method was trying (and failed) to do:
In legacy projects, I need to create native Java code. I create this code similar to Paulitex code. See that:
And the unit test:
One-liner solution (Java8) to delete all files and directories recursively including starting directory:
We use a comparator for reversed order, otherwise File::delete won't be able to delete possibly non-empty directory. So, if you want to keep directories and only delete files just remove the comparator in sorted() or remove sorting completely and add files filter: