Delete Directory in Java using Apache Commons IO
Tags: FileUtils Apache Commons Apache Commons IO Delete File Directory
In this Java tutorial we learn how to use the FileUtils class of Apache Commons IO library to delete a directory.
How to add Apache Commons IO library to your Java project
To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'commons-io:commons-io:2.8.0'
To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/
Delete a Directory using FileUtils.deleteDirectory()
The below code example shows you how to use the method FileUtils.deleteDirectory() to delete a directory and contents inside it recursively.
DeleteDirectory.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class DeleteDirectory {
public static void main(String... args) {
try {
File directoryToDelete = new File("D:\\TestData\\SubDirectory");
FileUtils.deleteDirectory(directoryToDelete);
System.out.println("Delete directory " + directoryToDelete + " success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Delete directory D:\TestData\SubDirectory success!
Delete a Directory using FileUtils.forceDelete()
Apache Commons IO also provides the method FileUtils.forceDelete() to force delete a directory and its sub directories, files.
DeleteDirectoryForce.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class DeleteDirectoryForce {
public static void main(String... args) {
try {
File directoryToDelete = new File("D:\\TestData\\SubDirectory");
FileUtils.forceDelete(directoryToDelete);
System.out.println("Delete directory " + directoryToDelete + " success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Delete directory D:\TestData\SubDirectory success!
Delete a Directory using FileUtils.deleteQuietly()
The method FileUtils.deleteQuietly() also deletes a directory and its contents. There are no exceptions thrown in case a file or directory cannot be deleted. The following example code shows you how to use the method.
DeleteDirectoryQuietly.java
import org.apache.commons.io.FileUtils;
import java.io.File;
public class DeleteDirectoryQuietly {
public static void main(String... args) {
File directoryToDelete = new File("D:\\TestData\\SubDirectory");
FileUtils.deleteQuietly(directoryToDelete);
System.out.println("Delete directory " + directoryToDelete + " success!");
}
}
Delete directory D:\TestData\SubDirectory success!
Happy Coding 😊