This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do you recursively list files in Java?

How do YOU recursively list all files in a directory in Java? Does the framework provide any utilities?

I’ve seen a lot of people come to fruition. But none came from the framework or NIO

Answer a

Java8 provides a nice Stream to process all the files in the directory tree.

Files.walk(Paths.get(path))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);
Copy the code

It provides a natural way to traverse a file. Because it is a flow, you can do all the good flow operations on the result, such as limiting, grouping, mapping, exiting early, and so on.

Update: I might point out that there is also files.find, which requires a BiPredicate, which might be more efficient if you need to check file properties

Files.find(Paths.get(path),
           Integer.MAX_VALUE,
           (filePath, fileAttr) -> fileAttr.isRegularFile())
        .forEach(System.out::println);
Copy the code

Note that while JavaDoc thinks this approach might be more efficient than files.walk, it’s actually the same, and you can see a difference in performance if you also retrieve file attributes in the filter. Finally, if you need to filter properties, use files.find, otherwise use files.walk, mainly because there are overloads and it’s more convenient.

Answer two

I made you a wheel

import java.io.File;

public class Filewalker {

    public void walk( String path ) {

        File root = new File( path );
        File[] list = root.listFiles();

        if (list == null) return;

        for ( File f : list ) {
            if ( f.isDirectory() ) {
                walk( f.getAbsolutePath() );
                System.out.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
                System.out.println( "File:"+ f.getAbsoluteFile() ); }}}public static void main(String[] args) {
        Filewalker fw = new Filewalker();
        fw.walk("c:\\"); }}Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/2…