Example 1: Java Program to delete an empty directory
import java.io.File;
class Main {
public static void main(String[] args) {
try {
// create a new file object
File directory = new File("Directory");
// delete the directory
boolean result = directory.delete();
if(result) {
System.out.println("Directory Deleted");
}
else {
System.out.println("Directory not Found");
}
} catch (Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have used the delete() method of the File class to delete the directory named Directory.
Here, if the directory is present, then the message Directory Deleted is shown. Otherwise, Directory not Found is shown.
Example 2: Delete a non-empty directory
In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can delete the directory.
In the above example, we have used the for-each loop to delete all the files present in the directory. Once, all files are deleted, we used the delete() method to delete the directory.
Example 3: Delete non-empty directory recursively
Here, suppose we have a non-empty directory named Directory. The Directory contains 2 files named file1.txt and file2.txt and a non-empty subdirectory named Subdirectory. Again, the Subdirectory contains a file named file11.txt.
Now, when we run the program, we will get the following output.
Directory\file1.txt is deleted Directory\file2.txt is deleted Directory\Subdirectory\file11.txt is deleted Directory\Subdirectory is deleted Directory is deleted
Here, first 2 files are deleted, then the recursive function delete the files inside the Subdirectory. Once, the Subdirectory is empty, it is deleted. And, finally the Directory is deleted.