How do you delete a directory with content in Java?
You can use the File class in Java along with recursion to delete a directory with content. Here is an example code:
import java.io.File;
public class DeleteDirectoryExample {
public static void main(String[] args) {
File directory = new File("path/to/directory");
deleteDirectory(directory);
}
public static void deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
file.delete();
}
}
}
directory.delete();
System.out.println("Directory deleted: " + directory.getAbsolutePath());
} else {
System.out.println("Directory not found: " + directory.getAbsolutePath());
}
}
}
Replace “path/to/directory” with the actual path of the directory you want to delete. This code will recursively delete all files and subdirectories within the directory until it is empty, and then delete the directory itself.