【发布时间】:2016-05-19 12:37:42
【问题描述】:
我的目标是创建一个具有 glob 功能的 FileScanner 并添加一些自定义过滤器功能(如最小或最大文件大小)。
我的第一次尝试是:
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:**/*.java");
Path path2 = Paths.get("c:/dummy");
try (final Stream<Path> stream = Files.list(path2)) {
stream.filter(pathMatcher::matches).forEach(FileProcessor::processFile);
}
为了在 c:\dummy 目录中只找到 *.java 文件,这很好用。但是我需要做什么才能只找到小于 1000 字节的 *.java 文件?
我的尝试是:
PathMatcher myMatcher = path -> {
// Do size comparision ...
return true;
};
Path path = Paths.get("c:/dummy");
try (final Stream<Path> stream = Files.list(path)) {
stream.filter(myMatcher::matches).forEach(FileProcessor::processFile);
}
但是有了这个解决方案,我不再有球了。
最后一次尝试是:
Path path3 = Paths.get("c:/dummy"); final PathMatcher pathMatcher2 = FileSystems.getDefault().getPathMatcher("glob:**/*.java");
Files.walkFileTree(path3, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher2.matches(path)) {
// Do size comparison
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
最后一个有效,但它看起来不太好,并且使用 SimpleFileVisitor 对象感觉有点复杂。
谁知道如何解决这个问题?
您好, 豪克
【问题讨论】:
-
Files.list()不会深入...
标签: java