Java-java编程思想的代码

Java-java编程思想的代码

夜无邪 发布于 2017-10-11 字数 2431 浏览 1067 回复 2
import java.util.regex.*;
import java.io.*;
import java.util.*;

public final 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(
new File(name).getName()).matches();
}
});
}
public static File[]
local(String path, final String regex) { // Overloaded
return local(new File(path), regex);
}
// A two-tuple for returning a pair of objects:
public static class TreeInfo implements Iterable<File> {
public List<File> files = new ArrayList<File>();
public List<File> dirs = new ArrayList<File>();
// The default iterable element is the file list:
public Iterator<File> iterator() {
return files.iterator();
}
void addAll(TreeInfo other) {
files.addAll(other.files);
dirs.addAll(other.dirs);
}
public String toString() {
return "dirs: " + PPrint.pformat(dirs) +
"nnfiles: " + PPrint.pformat(files);
}
}
public static TreeInfo
walk(String start, String regex) { // Begin recursion
return recurseDirs(new File(start), regex);
}
public static TreeInfo
walk(File start, String regex) { // Overloaded
return recurseDirs(start, regex);
}
public static TreeInfo walk(File start) { // Everything
return recurseDirs(start, ".*");
}
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 // Regular file
if(item.getName().matches(regex))
result.files.add(item);
}
return result;
}
// Simple validation test:
public static void main(String[] args) {

if(args.length==0)
for(File file : walk("."))
System.out.println(file);
}
} ///:~

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏爱自由 2017-10-23 2 楼

不知道你的为啥不行,你试试我的 class,共享地址:
http://116.255.186.66:8080/neo/code/todo.zip

有图有真相哦:

祝好,
斑驳敬上

泛泛之交 2017-10-22 1 楼

我的执行结果。不过我修改了一点,33,34行没有PPrint这个类,我改成return "dirs: " + (dirs) + "nnfiles: " + (files);

..classpath
..project
..settings.jsdtscope
..settings.svnall-wcprops
..settings.svnentries
..settings.svnprop-baseorg.eclipse.core.resources.prefs.svn-base
..settings.svnprop-baseorg.eclipse.jdt.core.prefs.svn-base
..settings.svnprop-baseorg.eclipse.jst.common.project.facet.core.prefs.svn-base
..settings.svnprop-baseorg.eclipse.wst.common.project.facet.core.xml.svn-base
..settings.svntext-base.jsdtscope.svn-base
..settings.svntext-baseorg.eclipse.core.resources.prefs.svn-base
..settings.svntext-baseorg.eclipse.jdt.core.prefs.svn-base
..settings.svntext-baseorg.eclipse.jst.common.project.facet.core.prefs.svn-base