【问题标题】:Java8 Glob PathMatcher with size filter带有大小过滤器的 Java8 Glob PathMatcher
【发布时间】: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


【解决方案1】:

根据要检查的文件名的属性,可以改用Files.find()

// Note that you can use a `PathMatcher` for the name instead if you want
final BiPredicate<Path, BasicFileAttributes> filter =
    (path, attrs) -> path.getFileName().toString().endsWith(".java") && attrs.size() <= 1000L;

try (
    final Stream<Path> = Files.find(baseDir, Integer.MAX_VALUE, filter);
) {
    // process the stream
}

你也可以使用Files.walk();但是,Files.find() 的优点是它会自动为您检索属性:Files.walk() 必须手动完成。

【讨论】:

  • 一点更正:你必须在“getFileName()”之后调用“toString”,因为getFileName返回一个Path对象,然后endsWith有不同的含义
  • @Hauke 哎呀...是的,我总是忘记那个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多