Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively list files in Java

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

like image 227
Quintin Par Avatar asked Jan 13 '10 11:01

Quintin Par


People also ask

How do I recursively list files?

Try any one of the following commands to see recursive directory listing: ls -R : Use the ls command to get recursive directory listing on Linux. find /dir/ -print : Run the find command to see recursive directory listing in Linux.

Are files walk recursive?

Files. walk returns a stream that is lazily populated with Path by recursively walking the file tree rooted at a given starting file. The file tree is traversed depth-first.

What does the files list () method in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

What is the use of recursive path?

A recursive path is a path that uses nested routes to display nested views by calling on the same component.


1 Answers

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: 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); 

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.

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.

like image 155
Brett Ryan Avatar answered Sep 28 '22 11:09

Brett Ryan