How do I recursively list all files under a directory in Java? Does the framework provide any utility?
I saw a lot of hacky implementations. But none from the framework or nio
How do I recursively list all files under a directory in Java? Does the framework provide any utility?
I saw a lot of hacky implementations. But none from the framework or nio
Java 8 provides a nice stream to process all files in a tree.
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: 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.
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: 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.
I think this should do the work:
This way you have files and dirs. Now use recursion and do the same for dirs (
File
class hasisDirectory()
method).I prefer using a queue over recursion for this kind of simple traversion:
Based on stacker answer. Here is a solution working in JSP without any external libraries so you can put it almost anywhere on your server:
Then you just do something like:
Java 7
will havehas Files.walkFileTree:There is now an entire Oracle tutorial on this question.