public class DirList { public static void main(String[] args) { File file=new File("."); String[] list; if(args.length==0) { list=file.list(); }else { list=file.list(new DirFilter(args[0]));//new DirFilter出代码因为实现了FilenameFilter接口;所以只要实现了该接口的类都可以;此处利用策略模式,提高了代码的灵活性 } Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);//忽略大小写字母将单词都放在一起排序 for(String dirName:list) { System.out.println(dirName); } } }
/**1.创建这个类的目的是提供accept供file.list方法使用;使list可以回调accept方法;进而决定哪些文件包含在列表中 */public class DirFilter implements FilenameFilter { private Pattern pattern; public DirFilter(String regex) { pattern=Pattern.compile(regex); } @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }
File.class源码: public String[] list(FilenameFilter filter) { String names[] = list(); if ((names == null) || (filter == null)) { return names; } List<String> v = new ArrayList<>(); for (int i = 0 ; i < names.length ; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } return v.toArray(new String[v.size()]); }
原文地址:https://www.cnblogs.com/zhangfengshi/p/9311479.html
时间: 2024-11-05 21:41:12