Files.walk.filter 和 Files.find 有什么区别?

What is the difference between Files.walk.filter and Files.find?

此代码搜索特定文件:

Stream<Path> findMyFile = Files.find(Paths.get("c:\temp\pathtest"), Integer.MAX_VALUE,(p, a) -> p.endsWith("test.txt") && a.isRegularFile());

Stream<Path> findMyFileSecond = Files.walk(Paths.get("c:\temp\pathtest"),Integer.MAX_VALUE).filter(p -> p.endsWith("test.txt"));

findMyFile.forEach(System.out::println);
findMyFileSecond.forEach(System.out::println);

两种结果都包含相同的文件,两种方法几乎同时完成。 JavaDoc 说明如下:

This method walks the file tree in exactly the manner specified by * the #walk walk method Compare to calling * java.util.stream.Stream#filter filter on the Stream * returned by {@code walk} method, this meth od may be more efficient by * avoiding redundant retrieval of the BasicFileAttributes

何时应将 walkfilter 结合使用以及何时应使用 find?什么是最佳实践?

我相信 walk() 如果您需要在应用过滤器或并行化流之前对目录列表应用一些中间操作,那将是有利的。

TL;DR:如果您需要按属性过滤掉 files/dirs - 使用 Files.find(),如果您不需要按文件属性过滤 - 使用 Files.walk()

详情

存在 轻微 差异,实际上在文档中进行了解释,但在某种程度上感觉完全错误。阅读源码一目了然:

  • Files.find:

    return StreamSupport.stream(...)
                            .onClose(iterator::close)
                            .filter(entry -> matcher.test(entry.file(), entry.attributes()))
                            .map(entry -> entry.file());
    
  • Files.walk:

    return StreamSupport.stream(...)
                            .onClose(iterator::close)
                            .map(entry -> entry.file());
    

这意味着,如果在您最终的过滤器中,您需要获取并验证文件属性 - File.find 可能会更快。那是因为使用 File.walk,您的过滤器回调将需要额外调用,例如Files.readAttributes(file, BasicFileAttributes.class),而 File.find - 属性已被检索并在过滤器回调中提供给您。

我刚刚在 Windows 上用我的示例 10K 文件在多个文件夹结构中进行了测试,方法是仅搜索 文件(即不包括文件夹):

// pre-Java7/8 way via recursive listFiles (8037 files returned): 1521.657 msec.
for (File f : new File(dir).listFiles()) {
    if (f.isDirectory()) {
        _getFiles(files, path, pattern);
    } else {
        ...
    }
}

// Files.walk(8037 files returned): 1575.766823 msec.
try (Stream<Path> stream = Files.walk(path, Integer.MAX_VALUE) {
    files = stream.filter(p -> {
        if (Files.isDirectory(p)) { return false; } // this extra check makes it much slower than Files.find
        ... 
    }).map(p -> p.toString()).collect(Collectors.toList());
}

// Files.find(8037 files returned): 27.606675 msec.
try (Stream<Path> stream = Files.find(path, Integer.MAX_VALUE, (p, a) -> !a.isDirectory())) {
    files = stream.filter(p -> { ... }).map(p -> p.toString()).collect(Collectors.toList());
}

// Files.walkFileTree(8037 returned): 27.443974 msec.
Files.walkFileTree(new File(path).toPath(), new SimpleFileVisitor<Path>() { 
    @Override
    public FileVisitResult visitFile(Path p, BasicFileAttributes attrs) throws IOException {
        ...
        return FileVisitResult.CONTINUE;
    }
});