Java is a method instance that deletes files directories and all files in a directory
- 2020-05-26 08:33:05
- OfStack
preface
The main function of this article is to delete a directory and all subdirectories and files under the directory.
File.delete()
Delete a file or empty directory! So to delete a directory and all the files and subdirectories in it, recursively delete.
The specific code example is 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 deletes all files in the directory and all files in the subdirectory
* @param dir Directory of files 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 deletes subdirectories in a directory
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty and can be deleted
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);
}
}
}
conclusion
The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.