且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中递归列出文件

更新时间:2022-03-10 23:08:21

Java 8 提供了一个很好的流来处理树中的所有文件.

Java 8 provides a nice stream to process all files in a tree.

Files.walk(Paths.get(path))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

这提供了一种自然的方式来遍历文件.由于它是一个流,您可以对结果执行所有不错的流操作,例如限制、分组、映射、提前退出等.

This provides a natural way to traverse files. Since it's a stream you can do all nice stream operations on the result such as limit, grouping, mapping, exit early etc.

更新:我可能会指出还有 Files.find 需要一个BiPredicate 如果您需要检查文件属性.

UPDATE: I might point out there is also Files.find which takes a BiPredicate that could be more efficient if you need to check file attributes.

Files.find(Paths.get(path),
           Integer.MAX_VALUE,
           (filePath, fileAttr) -> fileAttr.isRegularFile())
        .forEach(System.out::println);

请注意,虽然 JavaDoc 回避了这种方法可能比 Files.walk 它实际上是相同的,如果您是,则可以观察到性能差异还检索过滤器中的文件属性.最后,如果您需要过滤属性,请使用 Files.find,否则使用Files.walk,主要是因为有重载,而且更方便.

Note that while the JavaDoc eludes that this method could be more efficient than Files.walk it is effectively identical, the difference in performance can be observed if you are also retrieving file attributes within your filter. In the end, if you need to filter on attributes use Files.find, otherwise use Files.walk, mostly because there are overloads and it's more convenient.

测试:根据要求,我提供了许多答案的性能比较.查看 Github 项目,其中包含结果和测试用例.

TESTS: As requested I've provided a performance comparison of many of the answers. Check out the Github project which contains results and a test case.