Deleting a directory or file is a common task that we often perform while file handling. Deleting the unnecessary files and directories frees up space and keeps our system organized. In Java, the File class of the “java.io” package is used to create, manipulate, and delete files and directories. More specifically, the delete() method of this class lets us delete unnecessary files and directories conveniently. In addition to this, we can also use different libraries and frameworks to delete a specific directory.
In this tutorial, we’ll present a practical demonstration of different methods to delete a directory in Java.
How to Delete a Directory in Java
Java allows us to delete an empty or a non-empty directory (containing subdirectories or files). To do that, you can either use the in-built classes or third-party libraries/frameworks.
Method 1: Deleting a Directory Using delete() Method
To delete an empty directory in Java, use the built-in “delete()” method of the “File” class. By default, this method deletes the empty directories and files conveniently.
Example 1: Deleting an Empty Directory in Java
The below screenshot shows an empty directory whose path is “C:\Users\HP\Downloads\SourceDir\Javabeat”:
Suppose we want to delete this empty directory, for this, we use the delete() method as follows:
import java.io.File;
public class ExampleClass {
public static void main(String[] args) {
try {
String dirPath = "C:\\Users\\HP\\Downloads\\SourceDir\\Javabeat";
File dir = new File(dirPath);
boolean isDeleted = dir.delete();
if (isDeleted) {
System.out.println("The Selected Directory has been Deleted Successfully!");
} else {
System.out.println("The Selected Directory is Non-empty or Doesn't Exist");
}
} catch (Exception excep) {
excep.getStackTrace();
}
}
}
Code Explanation
- We import the File class from the “java.io” package.
- Next, we employ the try-catch statement to address the potential exceptions.
- In the try block, we specify the directory path and pass it to the File() constructor.
- After this, we invoke the delete() method on the specified path and store the retrieved result in a boolean variable.
- Finally, we use the if-else statement to ensure the directory’s deletion:
Example 2: Deleting a Non-Empty Directory in Java Using delete() Method
The delete() method can’t delete a non-empty directory(directly). To do that, first, we must empty/clean the directory and then delete it.
import java.io.File;
public class ExampleClass {
public static void removeDir(File dir) {
for (File subdir : dir.listFiles()) {
if (subdir.isDirectory()) {
removeDir(subdir);
}
subdir.delete();
}
}
public static void main(String[] args) {
try {
File dirPath = new File("C:\\Users\\HP\\Downloads\\SourceDir\\Javabeat");
removeDir(dirPath);
boolean isDeleted = dirPath.delete();
if (isDeleted) {
System.out.println("The Selected Directory has been Deleted Successfully!");
} else {
System.out.println("The Selected Directory Doesn't Exist");
}
} catch (Exception excep) {
excep.getStackTrace();
}
}
}
Code Explanation
- This time, we create a user-defined method named “removeDir()” to clean a non-empty directory.
- Within this method, we use the for loop with the listFiles() method to iterate over all the subdirectories and files within the specified directory.
- Next, we use the isDirectory() method with the if statement to check if the fetched path is a directory. If yes, call the removeDir() method recursively to delete the directory’s data/content.
- In the next line, we use the delete() method to delete the subdirectories and files.
This way, we can clean a non-empty directory and then delete it using the delete() method.
Method 2: Deleting a Directory Using deleteDirectory() Method
We can also use the deleteDirectory() method of the Apache Commons IO library to delete a directory in Java. However, to use this method, first, we need to add the given dependence in our Maven project:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
</dependency>
After adding the latest dependency to your Maven project, import the FileUtils class into your Java application using the import statement as follows:
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ExampleClass {
public static void main(String[] args){
File dirPath = new File("C:\\Users\\HP\\Downloads\\SourceDir\\Javabeat");
try {
FileUtils.deleteDirectory(dirPath);
dirPath.delete();
System.out.println("The Selected Directory has been Deleted Successfully!");
} catch (Exception excep) {
System.out.println("The Selected Directory is Non-empty or Doesn't Exist");
}
}
}
Code Explanation
- After importing the required classes, we use the File class constructor to specify the path of the directory to be deleted.
- In the next line, we invoke the deleteDirecotry() method of the FileUtils class to delete the directory recursively.
- In the end, we invoke the delete() method to remove the specified directory.
Method 3: Deleting a Directory Using deleteRecursively()
We can also use the deleteRecursively() method of the spring framework to delete any given directory. To use this method, first, we need to add its respective dependency(latest version) to our Maven project. To do that, simply copy-paste the following code into your pom.xml file:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.6</version>
</dependency>
Now import the FileSystemUtils class from the spring framework using the following import statement:
import org.springframework.util.FileSystemUtils;
import java.io.File;
public class DeleteDirExample {
public static void main(String[] args) {
String dirPath = "C:\\Users\\HP\\Downloads\\SourceDir\\Javabeat";
boolean deleteDir = FileSystemUtils.deleteRecursively(new File(dirPath));
if(deleteDir) {
System.out.println("The Selected Directory has been Deleted Successfully!");
}
else {
System.out.println("Failed to Delete the Selected Directory! Try Again!");
}
}
}
Code Explanation
- After importing the File and FileSystemUtils classes from their respective packages, we specify the directory’s path in a string-type variable.
- Next, we call the deleteRecursively() method on the specified directory path and store its result in a boolean variable.
- If the stated method retrieves true, this means the directory is deleted and hence we specify the message accordingly:
That’s all about deleting a directory in Java.
Final Thoughts
Deleting a directory is a common task in file management that we can do using Java. To delete a directory using Java, we can use methods like “delete()”, “deleteDirectory()”, and “deleteRecursively()”. The delete() method is the most convenient one that deletes an empty directory conveniently. We can also delete a non-empty directory using this method, but to do that, first, we need to clean that directory, as demonstrated in Example 2 of Method 1.
The “deleteDirectory()”, and “deleteRecursively()” belong to the Apache commons-io library and spring framework, respectively. Therefore, to use any of these methods, we need to add their respective Maven dependency to our “pom.xml” file.