If you try to delete a not empty folder, a java.nio.file.DirectoryNotEmptyException will be thrown. This tutorial will show 4 differents ways to delete folder recursively in Java :

github-mark
The code source is available on Github. Download the source

 

1- Native Java

JDK 1.0+

To delete a not empty folder, you must first delete its children. Below a recursive Java code to delete a given folder :

2- Walking the folder using WalkFileTree

JDK 1.7+

The java.nio.file.Files class provides walkFileTree to navigate in the folder. Below a code using it to delete recursively a given folder :

In this example, I used the SimpleFileVisitor class to walk the file. You can create your own “file visitor class” by implemeting¬† use The FileVisitor interface.

3- Using Apache commons IO

Since JDK 1.6 For Commons IO 2.4

Since JDK 1.5 For Commons IO 2.2

Appache Commons IO provides FileUtils to handle files and folders and delete them recursively. Below how to use it :

  • Download the dependency

If you are working on a Maven project, add the following to your pom.xml

If not, download the jar and add it to your classpath.

  • Delete folder recursively using FileUtils.deleteDirectory

4- Using SpringUtils

SpringUtil provides FileSystemUtils to copy and delete recursively folders.

  • Download the dependency

If you are working on a Maven project, add the following to your pom.xml

If not, download the jar and add it to your classpath.

  • Delete folder recursively using FileSystemUtils.deleteRecursively

github-mark
The code source is available on Github. Download the source