4

I want to get all directories & sub directories starting from current one.

I found one approach to achieve this with flatMap(). But it has one level deep:

    List<File> files =
            Stream.of(new File(".").listFiles())
                    .flatMap(file -> file.listFiles() == null ?
                            Stream.of(file) : Stream.of(file.listFiles()))
                    .collect(toList());
    System.out.println("Count: " + files.size());
    files.forEach(path -> System.out.println("Path: " + path));

If I'll have next project struckture:

enter image description here

it will show just:

Path: ./test/next1

How to achieve this with Java 1.8 full and deep as follows

Path: ./test/next1/next2/next3

catch23
  • 17,519
  • 42
  • 144
  • 217

1 Answers1

4

Use Files.walk:

List<Path> files = Files.walk(Paths.get(".")).collect(Collectors.toList());
System.out.println("Count: " + files.size());
files.forEach(System.out::println);

Note that this solution has a problem: if you encounter any exception during the traversal (for example, access denied to some nested folder), it will immediately fail with exception and there's no simple way to recover walking. Check, for example, this question. If recovering after exception is unnecessary in your case, this solution will work fine.

Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334