public class Directory { public static File[] local(File dir, final String regex) { // 获取当前路径下的子路径 return dir.listFiles(new FilenameFilter() { private Pattern pattern = Pattern.compile(regex); public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }); } // 获取当前路径下的子路径 public static File[] local(String path, final String regex) { return local(new File(path), regex); } // 迭代器 public static class TreeInfo implements Iterable<File> { public List<File> files = new ArrayList<File>(); public List<File> dirs = new ArrayList<File>(); public SimpleFormatter formater = new SimpleFormatter(); public Iterator<File> iterator() { return files.iterator(); } void addAll(TreeInfo other) { files.addAll(other.files); dirs.addAll(other.dirs); } public String toString() { return "dirs: " + dirs.toString() + "\n\nfiles: " + files.toString(); } } // 从给定路径开始遍历 public static TreeInfo walk(String start, String regex) { return recurseDirs(new File(start), regex); } // 从给定路径开始遍历 public static TreeInfo walk(File start, String regex) { return recurseDirs(start, regex); } // 从当前路径开始遍历 public static TreeInfo walk(String start) { return recurseDirs(new File(start), ".*"); } // 查找该目录下的子文件和子路径 static TreeInfo recurseDirs(File startDir, String regex) { TreeInfo result = new TreeInfo(); for (File item : startDir.listFiles()) { if (item.isDirectory()) { result.dirs.add(item); result.addAll(recurseDirs(item, regex)); } else { if (item.getName().matches(regex)) result.files.add(item); } } return result; } public static void main(String[] args) { if (args.length == 0) { System.out.println(walk(".")); } else { for (String arg : args) { System.out.println(walk(arg)); } } } }