Java File 利用递归得到文件夹下所有文件
File的方法:
解題思路:
1.判断文件路径是否存在,不存在直接结束方法
2.文件存在,转成文件数组,
3.遍历数组,去取文件命名,用String类的endsWith()方法,判断文件后缀是否是.txt
4.是的存入集合,不是的就使用递归,调用自己的方法,继续取文件名
(集合设置成全局静态属性:静态的特点,随着类的加载而加载,在内存中只有一份)
代码展示:
//全局静态属性,集合用来存储所有的文件名
static ArrayList<String> arrs = new ArrayList<>();
public static ArrayList job1(File file){
if(file.exists()) {
//获取文件数组
File[] files = file.listFiles();
//遍历文件数组,获得文件名
for (File f : files) {
//判断名字是不是。txt结尾
if (f.getName().endsWith(".txt")) {
arrs.add(f.getName());
} else {
job1(f);
}
}
return arrs;
}
System.out.println("文件路径错误");
return null;
}