Problem:

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.