Delete a file
Method 1: input a string for deletion
1 public static void delete (String path) {2 File file = new File (path); 3 // determine whether the File exists 4 if (! File. exists () {5 return; 6} 7 // yes. Delete 8 if (file. isFile () {9 file. delete (); 10 return; 11} 12 // is the directory 13 if (file. isDirectory () {14 String [] files = file. list (); 15 // Add the delimiter 16 if (! Path. endsWith (File. separator) {17 path = path + File. separator; 18} 19 20 for (int I = 0; I <files. length; I ++) {21 // recursive call to delete 22 delete (path + files [I]); 23} 24} 25 file. delete (); 26}
Method 2: input a file to delete the file.
1 public static void deleteAllFiles (File file) {2 // determine whether the File exists 3 if (! File. exists () {4 return; 5} 6 // yes. Delete 7 if (file. isFile () {8 file. delete (); 9 return; 10} 11 // directory 12 if (file. isDirectory () {13 // return the files and directories in this directory 14 File [] files = file. listFiles (); 15 // recursive call to delete 16 for (int I = 0; I <files. length; I ++) {17 deleteAllFiles (files [I]); 18} 19} 20 file. delete (); 21}
The difference between the two is that when a string is passed in, this string represents a directory, and you need to add separators to the files and directories under this directory.