File类和时间类的两道综合练习
来源:互联网 发布:warframe淘宝国际服 编辑:程序博客网 时间:2024/05/29 19:38
练习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 }
0 0
- File类和时间类的两道综合练习
- File类和时间类的两道综合练习
- File类和时间类的两道综合练习
- File类和时间类的两道综合练习
- File类和时间类的两道综合练习
- File类和时间类的两道综合练习
- 类的综合练习
- File类的综合应用
- file递归和一些综合练习
- File类的使用练习
- 1001 Java 类、抽象类、接口的综合小练习
- 027、类,抽象类,接口的综合小练习
- file类递归练习
- dom的综合练习
- 又到综合练习时间:递归
- 又到综合练习时间:递归
- 综合练习: 九九乘法表和排序
- 类和接口的综合案例
- 关于初学者上传文件到github的方法
- React安装与使用入门
- Python生成器学习笔记
- PHP弱类型的安全问题详细总结
- Windump教程-参数介绍
- File类和时间类的两道综合练习
- 详解卡尔曼滤波原理
- CCF认证 2015-09-2日期计算
- 【Python学习笔记】-Python基础入门
- MD5,SHA1,SHA256,NTLM,LM等Hash在线破解网站收集
- linux(预习二)
- 路在何方
- IE8+兼容经验小结
- 设置 IntelliJ IDEA 主题和字体的方法