Use Java to delete a folder in the disk
principle
Deleting a folder mainly calls the delete() method in File, but the delete() method can only delete standard files, so when deleting a file here, you need to use the idea of traversal and recursion to delete a folder
Code display
Show some below 内联代码片
.
public class TestDelete {
public static void main(String[] args) {
TestDelete test = new TestDelete();
String path = "E:\\creata";
test.deleteDir(path);
}
public void deleteDir(String path) {
//指定磁盘里需要删除的文件
File file = new File(path);
//遍历文件
File[] listFiles = file.listFiles();
for (File f:listFiles) {
//判断是标准的文件还是文件夹
if (f.isDirectory()) {
//标准文件夹运用运用递归把里面的标准文件在遍历一次
String path2 = f.getPath();
deleteDir(path2);
}else {
//不是标准文件直接调用delete()方法删除
f.delete();
}
}
//最后把空文件夹删除
file.delete();
}
}
to sum up
To delete a folder, you need to master the ideas of recursion and traversal. Because there are multiple files in a folder, the idea of traversal is also very important. Next, you can master the operation process of deleting a file:
generally traverse the file first, and then determine that the file is the standard The file is still a standard folder. If it is a standard file, call the delete() method directly to delete;
if it is a folder, then we need to use the recursive idea to traverse the file again and judge until the entire file is deleted; the
last step is to delete the file. Delete the outer folder and it's over