How can you implement recursive deletion of a folder in Java?
In Java, you can achieve recursive folder deletion by using the following method:
import java.io.File;
public class FileUtils {
public static void deleteFolder(File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
deleteFolder(file);
}
}
}
folder.delete();
}
public static void main(String[] args) {
File folder = new File("path/to/folder");
deleteFolder(folder);
}
}
In the given code, we’ve defined a deleteFolder method to recursively remove a folder. It first checks if the folder is a directory, then retrieves all files and subdirectories within it, recursively calling the deleteFolder method to delete them. Finally, the current folder is deleted. In the main method, we can call the deleteFolder method to delete a specified folder.