今天和大家分享一个方法,可用于得到指定目录中的指定文件类型列表:
***** Filenameilter :实现此接口的类实例可用于过滤器文件名 *****
使用 DirFilter implements FilenameFilter
去实现后将 accept 函数重写即可。 代码如下:
1 package net.cc.test; 2 3 import java.io.File; 4 import java.io.FilenameFilter; 5 6 /** 7 * @author test 8 * @create 2014-2-13下午03:17:39 9 * @version 1.0 10 */ 11 public class DirFilter implements FilenameFilter { 12 13 private String afn; 14 15 public DirFilter(String afn) { 16 // TODO Auto-generated constructor stub 17 this.afn = afn; 18 } 19 20 public boolean accept(File dir, String name) { 21 // TODO Auto-generated method stub 22 return name.indexOf(afn) != -1; 23 } 24 }
下面是 test 测试类:供参考
1 package net.cc.test; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.InputStream; 7 8 /** 9 * @author test 10 * @create 2014-2-13下午02:21:16 11 * @version 1.0 12 */ 13 public class Test1 { 14 15 public static void main(String[] args) { 16 17 String p1 = "D:\\apache-tomcat-aose\\bin"; 18 File path = new File(p1); 19 20 try { 21 String[] list = path.list(new DirFilter(".sh")); 22 for (String s : list) { 23 System.out.println(s); 24 } 25 } catch (Exception e) { 26 // TODO: handle exception 27 e.printStackTrace(); 28 } 29 } 30 }
----------------------------------------------------------------------------------------------------------
用一个匿名的内部类 同样可以做到以上的效果:
代码如下:
1 package net.cc.test; 2 3 import java.io.File; 4 import java.io.FilenameFilter; 5 6 /** 7 * @author test 8 * @create 2014-2-13下午03:52:28 9 * @version 1.0 10 */ 11 public class DirFilter2 { 12 13 public static FilenameFilter filter(final String afn) { 14 15 return new FilenameFilter() { 16 17 public boolean accept(File dir, String name) { 18 // TODO Auto-generated method stub 19 return name.indexOf(afn) != -1; 20 } 21 }; 22 } 23 24 public static void main(String[] args) { 25 26 String p1 = "D:\\apache-tomcat-aose\\bin"; 27 File path = new File(p1); 28 29 try { 30 String[] lists = path.list(DirFilter2.filter(".sh")); 31 for (String s : lists) { 32 System.out.println(s); 33 } 34 } catch (Exception e) { 35 // TODO: handle exception 36 e.printStackTrace(); 37 } 38 } 39 }
原文:http://www.cnblogs.com/zhonghuazhi/p/3548234.html