List only folders of certain depth using Java 8 streams
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()));
Here is a solution that works with arbitrary minDepth
and maxDepth
also larger than 1. Assuming minDepth >= 0
and minDepth <= maxDepth
:
final int minDepth = 2;
final int maxDepth = 3;
final Path rootPath = Paths.get("/path/to/stuff/");
final int rootPathDepth = rootPath.getNameCount();
Files.walk(rootPath, maxDepth)
.filter(e -> e.toFile().isDirectory())
.filter(e -> e.getNameCount() - rootPathDepth >= minDepth)
.forEach(System.out::println);
To accomplish what you asked originally in the question of listing "...only folders of certain depth...", just make sure minDepth == maxDepth
.