使用FilenameFilter过滤出特定格式的文件

过滤类(策略模式)

 1 /**
 2  * @author Ldl 
 3  * @since 1.0.0
 4  */
 5 public class DirFilter implements FilenameFilter {
 6 
 7     private Pattern pattern;
 8 
 9     /**
10      * 构造函数
11      */
12     public DirFilter(String regex) {
13         pattern = Pattern.compile(regex);
14     }
15 
16     /**
17      * @Author Ldl
18      * @Date 2017年3月28日
19      * @since 1.0.0
20      * @param dir
21      * @param name
22      * @return
23      * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
24      */
25     @Override
26     public boolean accept(File dir, String name) {
27         return pattern.matcher(name).matches();
28     }
29 
30 }

 

测试类

 1 /**
 2  * @author Ldl 
 3  * @since 1.0.0
 4  */
 5 public class DirList {
 6 
 7     /**
 8      * DirList.main()
 9      * @Author Ldl
10      * @Date 2017年3月28日
11      * @since 1.0.0
12      * @param args like ^.*?\.(jpg|xml|png|gif)$
13      */
14     public static void main(String[] args) {
15         File path = new File("E:\\");
16         String[] list = null;
17 
18         if (args.length == 0) {
19             list = path.list();
20         } else {
21             list = path.list(new DirFilter(args[0]));
22         }
23         if (list != null) {
24             Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
25             for (String dirItem : list) {
26                 System.out.println(dirItem);
27             }
28         }
29     }
30 
31 }

 

posted on 2017-04-18 15:34  AlphaGo1号  阅读(425)  评论(0)    收藏  举报

导航