In this tutorial I will explain the steps to delete a directory in Java.
The delete() method of the File class deletes the files and empty directory represented by the current File object. If a directory is not empty or has files, then it can’t be deleted directly. First, empty the directory, then delete the folder.
Suppose there exists a directory with path Desktop\Test. The next image displays the files and directories present inside Test folder. The Test directory has folders Demo_1, Demo_2, and Demo_3.

The next java programs illustrate how to delete a directory. This example uses a recursive method to delete the directory and all its contents, including subdirectories.
package org.example;
import java.io.File;
public class DeleteDirectoryDemo {
public static void main(String[] args) {
String directoryPath = "C:\\Users\\Vibha\\Desktop\\Test";
//Create a file object for the directory
File directory = new File(directoryPath);
if(directory.exists()&& directory.isDirectory()) {
boolean successful = deleteDirectory(directory);
if (successful) {
System.out.println("Directory deleted :" + directoryPath);
} else {
System.out.println("Failed to delete Directory :" + directoryPath);
}
} else {
System.out.println("Directory does not exists :" + directoryPath);
}
}
private static boolean deleteDirectory(File directory) {
File[] allContents = directory.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
System.out.println("File deleted :" + file);
}
}
return directory.delete();
}
}
Explanation
Step 1 – Check if the directory exists.
if(directory.exists()&& directory.isDirectory())
Step 2 – List files in the directory.
File[] allContents = directory.listFiles();
Step 3 – Delete files and subdirectories recursively
for (File file : allContents) {
deleteDirectory(file);
System.out.println("File deleted :" + file);
}
}
Step 4 – Delete the empty directory.
directory.delete();
The output of the above program is

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!