package com.seven.file;
import java.io.File;
public class Recursion {
public static void main(String[] args) {
//递归遍历
ergodicFile(new File("D:\\test"));
//递归删除
deleteFiles(new File("D:\\testss"));
}
private static void deleteFiles(File file) {
if (!file.exists())return;
File[] files = file.listFiles();
if (files==null||files.length==0)return;
for (File f : files) {
if (f.isDirectory()){
deleteFiles(f);
}else{
System.out.println(f.getAbsolutePath());
f.delete();
}
}
System.out.println(file.getAbsolutePath());
file.delete();
}
private static void ergodicFile(File file) {
if (!file.exists()) return;//路径不存在也返回
System.out.println(file.getAbsolutePath());
File[] files = file.listFiles();
if (files==null||files.length==0) return;//没有内容也返回
for (File f:files) {
if (f.isDirectory()){
ergodicFile(f);
}else{
System.out.println(f.getAbsolutePath());
}
}
}
}
删除返回结果
D:\testss\a.txt
D:\testss\accsd.txt
D:\testss\Afdse.txt
D:\testss\arewger.txt
D:\testss\b.txt
D:\testss\person.person
D:\testss\q.txt
D:\testss\test.txt
D:\testss\testeeee\fe.txt
D:\testss\testeeee\fefgregre.properties
D:\testss\testeeee\新建文件夹\新建文件夹\新建 RTF 文档.rtf
D:\testss\testeeee\新建文件夹\新建文件夹
D:\testss\testeeee\新建文件夹\新建文本文档.txt
D:\testss\testeeee\新建文件夹
D:\testss\testeeee
D:\testss\w.txt
D:\testss