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.
import java.io.File;
class Main {
public static void main(String[] args) {
try {
// create a new file object
File directory = new File("Directory");
// list all the files in an array
File[] files = directory.listFiles();
// delete each file from the directory
for(File file : files) {
System.out.println(file + " deleted.");
file.delete();
}
// delete the directory
if(directory.delete()) {
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 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
import java.io.File;
class Main {
public static void deleteDirectory(File directory) {
// if the file is directory or not
if(directory.isDirectory()) {
File[] files = directory.listFiles();
// if the directory contains any file
if(files != null) {
for(File file : files) {
// recursive call if the subdirectory is non-empty
deleteDirectory(file);
}
}
}
if(directory.delete()) {
System.out.println(directory + " is deleted");
}
else {
System.out.println("Directory not deleted");
}
}
public static void main(String[] args) {
try {
// create a new file object
File directory = new File("Directory");
Main.deleteDirectory(directory);
} catch (Exception e) {
e.getStackTrace();
}
}
}
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.