获取一个目录下的所有文件(按时间排序)


网摘

 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