排序式列出指定目录下的指定文件/夹——《Thinking in Java》随笔027

 1 //: SortedDirList.java
 2 /// 此程序可以对一个目录进行列出。
 3 
 4 package c10;
 5 
 6 import java.io.File;
 7 import java.io.FilenameFilter;
 8 import java.util.Arrays;
 9 import java.util.Comparator;
10 
11 /**
12 *    @time:         上午11:52:04
13 *    @date:         2017年4月29日
14 *    @auther:    skyfffire
15 *    @version:    v0.1
16 *
17 *    可排序式读入文件目录,传值sort=-1为降序
18 *    传值sort=1为传统升序(按照ASCII码)
19 */
20 public class SortedDirList {
21     private File path = null;
22     private String[] list = null;
23     private int sort = 1;
24     
25     /**
26      * 
27      * @param filesPath        要读取的路径
28      * @param afn            过滤字符,如果为null则不过滤
29      * @param sort            排序方式,-1降序,1升序
30      */
31     public SortedDirList(final String filesPath, 
32             final String afn, int sort) {
33         this.sort = sort;
34         path = new File(filesPath);
35         
36         if (afn == null) {
37             list = path.list();
38         } else {
39             list = path.list(new FilenameFilter() {
40                 @Override
41                 public boolean accept(File dir, String name) {
42                     String n = new File(name).getName();
43                     
44                     return n.indexOf(afn) != -1;
45                 }
46             });
47         }
48         
49         /**
50          * 手动实现sort方法的内部排序机制,这样可以动态地进行升/降排序
51          */
52         Arrays.sort(list, new Comparator<String>() {
53             @Override
54             public int compare(String o1, String o2) {
55                 return sort * (o1.compareTo(o2));
56             }
57         });
58     }
59     
60     /**
61      * 用于打印list
62      */
63     void print() {
64         for (String nowPath : list) {
65             System.out.println(nowPath);
66         }
67     }
68 
69     /**
70      * @return the sort
71      */
72     public int getSort() {
73         return sort;
74     }
75 
76     /**
77      * @param sort the sort to set
78      */
79     public void setSort(int sort) {
80         this.sort = sort;
81     }
82     
83     public static void main(String[] args) {
84         // 不进行过滤
85         SortedDirList sdl = new SortedDirList("C:\", null, 1);
86         
87         sdl.print();
88     }
89 }
90 
91 ///:~

我以自己的C盘根目录为例,升序排序的结果为:

$Recycle.Bin
BOOTNXT
Documents and Settings
OneDriveTemp
PerfLogs
Program Files
Program Files (x86)
ProgramData
QMDownload
Recovery
SymCache
System Volume Information
Users
Windows
bootmgr
pagefile.sys
swapfile.sys

降序排序的结果为:

swapfile.sys
pagefile.sys
bootmgr
Windows
Users
System Volume Information
SymCache
Recovery
QMDownload
ProgramData
Program Files (x86)
Program Files
PerfLogs
OneDriveTemp
Documents and Settings
BOOTNXT
$Recycle.Bin

可以只改动一个正负号就能快速地修改排序方式。

原文地址:https://www.cnblogs.com/skyfffire/p/6784901.html