Want to delete subfolders and its contents from a folder using Java? We have shared a Java program to delete the folders.
Copy the below program and execute it to delete the folders in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import java.io.File; /** * Java Program to delete directory with sub directories and files on it */ public class FileDeleteDemo { public static void main(String args[]) { deleteDirectory("one"); deleteDirectory(new File("one")); } /* * Right way to delete a non empty directory in Java */ public static boolean deleteDirectory(File dir) { if (dir.isDirectory()) { File[] children = dir.listFiles(); for (int i = 0; i < children.length; i++) { boolean success = deleteDirectory(children[i]); if (!success) { return false; } } } // either file or an empty directory System.out.println("removing file or directory : " + dir.getName()); return dir.delete(); } /* * Incorrect way to delete a directory in Java */ public static void deleteDirectory(String file) { File directory = new File(file); File[] children = directory.listFiles(); for (File child : children) { System.out.println(child.getAbsolutePath()); } boolean result = directory.delete(); if (result) { System.out.printf("Directory '%s' is successfully deleted", directory.getAbsolutePath()); } else { System.out.printf("Failed to delete directory '%s' %n", directory.getAbsolutePath()); } } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.