在 Java 中递归列出文件 [英] Recursively list files in Java

查看:38
本文介绍了在 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 中递归列出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆