Roufid

4 ways to delete folder recursively in Java

Java

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 :


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 :

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.

4- Using SpringUtils

SpringUtil provides FileSystemUtils to copy and delete recursively folders.

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.


The code source is available on Github. Download the source