视频链接:16.29 递归遍历和递归删除_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Tz4y1X7H7?spm_id_from=333.788.videopod.episodes&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5&p=29
1.文件夹的递归遍历
public class ListDirectoryDemo01 {
public static void main(String[] args) {
listDirectory(new File("C:\\qqq"));
}
public static void listDirectory(File directory){
System.out.println(directory.getAbsoluteFile());
File[] files = directory.listFiles();
if (files!=null){
for (File file : files) {
if (file.isDirectory()){
listDirectory(file);//递归操作
}else {
System.out.println(file.getAbsoluteFile());
}
}
}
}
}
2.文件夹的递归删除
//案例2:递归删除文件夹
public class ListDirectoryDemo01 {
public static void main(String[] args) {
deleteDirectory(new File("C:\\qqq"));
}
public static void deleteDirectory(File directory){
File[] files = directory.listFiles();
if (files!=null){
for (File file : files){
if (file.isDirectory()){
deleteDirectory(file);//递归操作
}else {
System.out.println("删除: " + file.getAbsoluteFile() +" " + file.delete());
}
}
}
System.out.println("删除: " + directory.getAbsoluteFile() + " " + directory.delete());
}
}