Preface
The main function of this article is to delete a directory and all subdirectories and files in a directory. The knowledge points involved are: File.delete() is used to delete a "a file or an empty directory"! Therefore, to delete a directory and all files and subdirectories in it, recursively delete it.
Specific code examples are as follows:
import java.io.File;public class DeleteDirectory { /** * Delete empty directory* @param dir The directory path to be deleted*/ private static void doDeleteEmptyDir(String dir) { boolean success = (new File(dir)).delete(); if (success) { System.out.println("Successfully deleted empty directory: " + dir); } else { System.out.println("Failed to delete empty directory: " + dir); } } /** * Recursively delete all files in the directory and all files in the subdirectories* @param dir File directory to be deleted* @return boolean Returns "true" if all deletions were successful. * If a deletion fails, the method stops attempting to * delete and returns "false". */ private static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); //Recursively delete the subdirectories in the directory for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is empty at this time, you can delete return dir.delete(); } /** *Test*/ public static void main(String[] args) { doDeleteEmptyDir("new_dir1"); String newDir2 = "new_dir2"; boolean success = deleteDir(new File(newDir2)); if (success) { System.out.println("Successfully deleted populated directory: " + newDir2); } else { System.out.println("Failed to delete populated directory: " + newDir2); } }}Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.