练习1:
获取指定目录下(包含子目录)所有的某一种类型的文件
分析:
1.指定路径并获取其下的文件对象
2.要判断给定的目录是否为空
3.要判断给定路径下获取的目录是否为空
4.判断是否是某种文件
5.因为要求目录下的所有的文件,因此要区分到底是文件夹还是文件,使用递归思想
1 public class Test {
2
3 public static void main(String[] args) {
4 //创建一个file对象,里面存放指定的目录
5 File names = new File("D:\\文\\浏览器下载");
6 String suffix = ".pdf";
7 getImgList(names,suffix);
8
9
10 }
11
12 private static void getImgList(File names,String suffix) {
13
14 if(!names.exists())
15 throw new RuntimeException("没有这个文件夹");
16 //遍历所有的文件对象来进行操作
17 File[] f = names.listFiles();
18 if(f == null)
19 return ;
20 for(File name : f){
21 if(name.isFile()){
22 if(name.getName().endsWith(suffix))
23 System.out.println(name.getAbsolutePath());
24 }else if(name.isDirectory()){
25 getImgList(name,suffix);
26 }
27 }
28 }
29
30 }
------------------------------------------------------
练习2:
获取指定目录下(包含子目录)所有在2016年修改的文件
分析:
1.获取并进行一系列的判断
2.将获得的时间格式化,判断是否等于2016年.
3.因为是所有的文件,需要去使用到递归
1 public class Test {
2
3 public static void main(String[] args) {
4 //
5 String year = "2016";
6 File dir = new File("D:\\文档\\浏览器下载");
7 getFileListByYear(dir,year);
8
9 }
10
11 private static void getFileListByYear(File dir,String year) {
12 //先判断这个文件夹是否存在,不存在的话,抛出异常
13 if(!dir.exists())
14 throw new RuntimeException("您指定的目录不存在!");
15 //对文件夹进行遍历
16 File[] names = dir.listFiles();
17 //如果遍历文件夹得到的结果是空的,则结束
18 if(names == null) return;
19 for(File name : names){
20 if(name.isFile()){
21 //输出的是最后一次修改时间的毫秒时
22 long time = name.lastModified();
23 //将毫秒时格式化为我们喜欢的格式
24 Date date = new Date(time);
25 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
26 String newYear = sdf.format(date);
27 if(newYear.equals(year)){
28 System.out.println(name.getName());
29 }
30 }else{
31 getFileListByYear(name, year);
32 }
33
34 }
35
36
37 }
38
39 }