Search code examples
javajava-8directorytraversal

List only folders of certain depth using Java 8 streams


Considering there is the "new" streams API in Java 8 I can use Files.walk to iterate over a folder. How can I only get the child folders of my given directory if using this method or maybe depth=2?

I currently have this working example, which sadly also prints the root path as all "subfolders".

Files.walk(Paths.get("/path/to/stuff/"))
     .forEach(f -> {
        if (Files.isDirectory(f)) {
            System.out.println(f.getName());
        }
     });

I therefore reverted to the following approach. Which stores the folders in memory and needs handling of the stored list afterwards, which I would avoid and use lambdas instead.

File[] directories = new File("/your/path/").listFiles(File::isDirectory);

Solution

  • To list only sub-directories of a given directory:

    Path dir = Paths.get("/path/to/stuff/");
    Files.walk(dir, 1)
         .filter(p -> Files.isDirectory(p) && ! p.equals(dir))
         .forEach(p -> System.out.println(p.getFileName()));