以Java的形式递归列出文件 [英] Recursively list files in Java

查看:251
本文介绍了以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.

UPDATE :我可能会指出还有 Files.find ,其中包含 BiPredicate 如果你需要检查文件属性可以更有效率。

UPDATE: I might point out there is also Files.find which takes a BiPredicate that could can 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's overloads and it's more convenient.

TESTS :根据要求,我提供了许多答案的性能比较。查看包含结果和测试用例的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天全站免登陆