递归列出Java中的文件

Recursively list files in Java(递归列出Java中的文件)

本文介绍了递归列出Java中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何递归列出 Java 目录下的所有文件?该框架是否提供任何实用程序?

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

我看到了很多 hacky 实现.但没有来自框架或 nio

I saw a lot of hacky implementations. But none from the framework or nio

推荐答案

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.

这篇关于递归列出Java中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:递归列出Java中的文件

基础教程推荐