Starting with JDK 8, the Files class has been enriched with two walk() methods. These methods return a Stream that is lazily populated with Path. It does this by walking the file tree that's rooted at a given starting file using the given maximum depth and options:
public static Stream<Path> walk(
Path start, FileVisitOption...options)
throws IOException
public static Stream<Path> walk(
Path start, int maxDepth, FileVisitOption...options)
throws IOException
For example, let's display all the paths from D:/learning that start with D:/learning/books/cdi:
Path directory = Paths.get("D:/learning");
Stream<Path> streamOfPath = Files.walk(
directory, FileVisitOption.FOLLOW_LINKS);
streamOfPath.filter(e -> e.startsWith("D:/learning/books/cdi"))
.forEach(System.out::println);
Now, let's compute the size in bytes for a folder (for example, D:/learning):
long folderSize = Files.walk(directory)
.filter(f -> f.toFile().isFile())
.mapToLong(f -> f.toFile().length())
.sum();
This method is weakly consistent. It doesn't freeze the file tree during the iteration process. The potential updates to the file tree may or may not be reflected.