Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 directory tree as stream


How to get directory tree as stream in Java 8? Each release brings many JVM improvements, not only on language level. This post shows new Java NIO feature.

When new Java versions are released, most people focus only on language features, forgetting about JVM as a platform. But with each new release there are many improvements in areas of tooling, garbage collection, and, JDK itself.

In the following example we’re going to show how to apply one of a few small improvements to java.nio.file.Files that allows to get directory tree as stream to process later in functional way:

  • Stream<Path> walk(Path start, int maxDepth, FileVisitOption… options)

There are two walk methods, but the one without maxDepth just calls the other one with maxDepth set to Integer.MAX_VALUE.

The method returns lazy stream of paths that is realized when consumed, which means if you don’t use it then it won’t traverse the filesystem. The stream is constructed by traversing directories tree using depth-first algorithm. FileVisitOption can be used to make the method to follow links – by default it doesn’t.


Enough talking, let’s see the code:


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.lang.System.out;

public class ListDirectoryTreeExample {

    public static void main(String[] args) throws IOException {
        String dirName = null;
        int searchDepth = 20;

        switch (args.length) {
            case 2: searchDepth = Integer.parseInt(args[1]);
                // fallthrough to set also dirName:
            case 1: dirName = args[0];
                out.println("Usage: ListDirectoryTreeExample dir [depth]");

        Path path = Paths.get(dirName);
        out.printf("Content of %s with depth %d:%n",
                dirName, searchDepth);

        // Use try-clause to close the stream immediately:
        try (Stream<Path> paths = Files.walk(path, searchDepth)) {

Pretty simple and convenient. In this example we’ve only printed the directory tree, but you can apply different functions here as on any other stream (e.g. do paging of results – skip(5).take(10)).

Running the program with arguments “/opt” and “2” gives the following result:

Content of /opt with depth 2:

In subsequent posts we’ll explore Java NIO so stay tuned! :-)

Share with the World!