1. 程式人生 > >File類和時間類的兩道綜合練習

File類和時間類的兩道綜合練習

練習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 }