//需要格式打印类 PPrint.java |
public class Directory { |
|
public static File[] local(File dir, final String regex) { |
return dir.listFiles( new FilenameFilter() { |
private Pattern pattern = Pattern.compile(regex); |
@Override |
public boolean accept(File dir, String name) { |
// TODO Auto-generated method stub |
return pattern.matcher( new File(name).getName()).matches(); |
} |
}); |
} |
@SuppressWarnings ( "static-access" ) |
public static void main(String[] args) { |
if (args.length == 0 ) { |
System.out.println( "===============AllFile=============" ); |
System.out.println( new TreeInfo().walk( "." ,RegexString.SUFFIX_ALL)); //,RegexString.SUFFIX_ALL表示正则表达式 |
System.out.println( "===============.java===============" ); |
System.out.println( new TreeInfo().walk( "." ,RegexString.SUFFIX_JAVA)); |
System.out.println( "===============.class===============" ); |
System.out.println( new TreeInfo().walk( "." ,RegexString.SUFFIX_CLASS)); |
|
} else { |
for (String arg : args) { |
System.out.println( new TreeInfo().walk(arg, ".*" )); |
} |
} |
} |
public static class TreeInfo implements Iterable<File>{ |
public List<File> files = new ArrayList<File>(); //文件 |
public List<File> dirs = new ArrayList<File>(); //目录 |
|
@Override |
public Iterator<File> iterator() { |
// TODO Auto-generated method stub |
return files.iterator(); |
} |
void addAll(TreeInfo other) { //加入集合 |
files.addAll(other.files); |
dirs.addAll(other.dirs); |
} |
public String toString() { |
return "dirs: " + PPrint.pformat(dirs) + "\n\nfiles: " + PPrint.pformat(files); |
} |
public static TreeInfo walk(String start,String regex) { //文件目录,正则表达式(文件格式) |
return recurseDirs( new File(start),regex); |
} |
private static TreeInfo recurseDirs(File startDir, String regex) { |
// TODO Auto-generated method stub |
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; |
} |
} |
} |