獲取一個目錄下的所有文件(按時間排序)


網摘

 1 public static void main(String[] args) {
 2     String path = "d:\\test";
 3     List<File> list = getFileSort(path);
 4     for(File file:list){
 5         Long time =file.lastModified();
 6         Calendar cd = Calendar.getInstance();
 7         cd.setTimeInMillis(time);
 8         System.out.println(file.getName()+":"+cd.getTime());
 9     }
10 }
11 // 獲取目錄下所有文件(按時間排序)
12 public static List<File> getFileSort(String path) {
13     List<File> list = getFiles(path, new ArrayList<File>());
14     if (list != null && list.size() > 0) {
15         Collections.sort(list, new Comparator<File>() {
16             public int compare(File file, File newFile) {
17                 if (file.lastModified() < newFile.lastModified()) {//降序<;升序> 18                     return 1;
19                 } else if (file.lastModified() == newFile.lastModified()) {
20                     return 0;
21                 } else {
22                     return -1;
23                 }
24             }
25         });
26     }
27     return list;
28 }
29 // 獲取目錄下所有文件
30 public static List<File> getFiles(String realpath, List<File> files) {
31     File realFile = new File(realpath);
32     if (realFile.isDirectory()) {
33         File[] subfiles = realFile.listFiles();
34         for (File file : subfiles) {
35             if (file.isDirectory()) {
36                 getFiles(file.getAbsolutePath(), files);
37             } else {
38                 files.add(file);
39             }
40         }
41     }
42     return files;
43 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM