1// delete a directory in java using recursion or recursively
2import java.io.File;
3public class DeleteDirectoryRecursively
4{
5 public static void main(String[] args)
6 {
7 String strFolder = "B:\New folder";
8 //delete folder recursively
9 deleteRecursive(new File(strFolder));
10 }
11 public static void deleteRecursive(File fl)
12 {
13 if(!fl.exists())
14 return;
15 // if directory call recursively
16 if(fl.isDirectory())
17 {
18 for(File file : fl.listFiles())
19 {
20 // recursive call
21 deleteRecursive(file);
22 }
23 }
24 // delete files and empty directory
25 fl.delete();
26 System.out.println("Deleted file/directory: " + fl.getAbsolutePath());
27 }
28}
1boolean deleteDirectory(File directoryToBeDeleted) {
2 File[] allContents = directoryToBeDeleted.listFiles();
3 if (allContents != null) {
4 for (File file : allContents) {
5 deleteDirectory(file);
6 }
7 }
8 return directoryToBeDeleted.delete();
9}