Files are deleted as subfiles.
First, I will briefly describe some basics: (the folder mentioned below is the directory. I did not know what the directory is at first, and then I learned that the directory is the folder ).
1. First, we will introduce the basic usage of the delete () method.
Create a File object first, for example, File file = new File ("C:/text"). text is a folder;
① When the text in the folder is empty (that is, there is nothing in it), call the file. delete () method to delete the file and return true.
② When the text in the folder is not empty (there are folders or files in it) and the file. delete () method is called, the file is not deleted and false is returned.
③ When there is something in the folder, it cannot be deleted directly.
2. recursion: A simple understanding is to call yourself.
3. encapsulate a method to delete a folder, that is, its subfiles:
1 public static void deleteDir (File file) {2 if (file. exists () {// determines whether the passed object exists. If yes, run the following code 3 File [] fileList = file. listFiles (); 4 for (File f: fileList) {5 if (f. isDirectory () {// 6 deleteDir (f) When the file is a folder; // recursive 7} else {8 System is used here. out. println ("the deleted file is:" + f. getName (); 9 f. delete (); 10} 11} 12 System. out. println ("the deleted folder is:" + file. getName (); // Delete the empty folder 13 file on the outermost layer. delete (); 14} else {15 System. out. println ("the file you deleted does not exist"); 16} 17}
4. Call the following in the main function:
1 public static void main(String[] args) {2 File file = new File("C:/text");3 deleteDir(file);4 }