Delete File in Java using Apache Commons IO
Tags: FileUtils Apache Commons Apache Commons IO Delete File
In this Java tutorial we learn how to use the FileUtils utility class of Apache Commons IO library to delete a file.
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 File using FileUtils.forceDelete() method
The method FileUtils.forceDelete() will throw an Exception if the file cannot be deleted. The following code example shows you how to use the method.
DeleteFileForce.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class DeleteFileForce {
public static void main(String... args) {
try {
File fileToDelete = new File("D:\\TestData\\SubDirectory\\data.txt");
FileUtils.forceDelete(fileToDelete);
System.out.println("Delete file " + fileToDelete + " success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Delete file D:\TestData\SubDirectory\data.txt success!
Delete a File using FileUtils.deleteQuietly() method
The method FileUtils.deleteQuietly() won’t throw any exception if the file cannot be deleted. You can learn how to use the method via the following example program.
DeleteFileQuietly.java
import org.apache.commons.io.FileUtils;
import java.io.File;
public class DeleteFileQuietly {
public static void main(String... args) {
File fileToDelete = new File("D:\\TestData\\SubDirectory\\data.txt");
FileUtils.deleteQuietly(fileToDelete);
System.out.println("Delete file " + fileToDelete + " success!");
}
}
Delete file D:\TestData\SubDirectory\data.txt success!
Happy Coding 😊