Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java 8 directory tree as stream

farenda 2016-03-25 0

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.

Solution:

Enough talking, let’s see the code:

package com.farenda.java.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

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];
                break;
            default:
                out.println("Usage: ListDirectoryTreeExample dir [depth]");
                System.exit(1);
        }

        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)) {
            paths.forEachOrdered(out::println);
        }
    }
}

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:
/opt
/opt/vagrant
/opt/vagrant/embedded
/opt/vagrant/bin
/opt/google
/opt/google/chrome-beta
/opt/google/chrome-unstable
/opt/google/chrome
/opt/google/talkplugin

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

Share with the World!
Categories Java Tags java, java-io
Previous: Java external process
Next: MongoDB 3 – connect from Java

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored