How to delete folders in Java
File file = new file ("D:/defonds/Temp ");
If "D:/defonds/Temp" is an empty directory, it can be deleted successfully. However, if it is a non-empty directory, it cannot be deleted successfully. You must delete its sub-files (directories) to delete them successfully. You can use the following methods to successfully delete a non-empty folder:
// Recursively Delete the private void deletefile (File file) {If (file. exists () {// determine whether the object exists if (file. isfile () {// checks whether the file is a file. delete (); // delete file} else if (file. isdirectory () {// otherwise, if it is a directory file [] files = file. listfiles (); // declare all files in the directory []; for (INT I = 0; I <files. length; I ++) {// traverse all files in the directory this. deletefile (files [I]); // use this method to iterate each file} file. delete (); // Delete folder} else {system. out. println ("the deleted file does not exist ");}}
You can also use the following method:
Public static void deleteallfilesofdir (file path) {If (! Path. exists () return; If (path. isfile () {path. delete (); return;} file [] files = path. listfiles (); For (INT I = 0; I