In Java, Files.walk(start) returns a Stream<Path> of start itself and everything below it, visited depth-first. Each folder appears before its contents, but siblings come in no particular order.
An overload takes a maxDepth to limit how deep it goes, and FileVisitOption.FOLLOW_LINKS to follow symbolic links. Like all directory streams, close it with try-with-resources.
A static method of the final utility class java.nio.file.Files, available since Java 8. Call it on the class name, as in Files.walk(...), after import java.nio.file.Files;. You never create a Files object.
Syntax
Unlimited depth, or a maximum depth and options:
Java
try (Stream<Path> tree = Files.walk(root)) { ... }
try (Stream<Path> top = Files.walk(root, 1)) { ... } // root + children
Files.walk(root, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS);
Call
What it does
Files.walk(p)
Whole tree, start included.
Files.walk(p, 1)
Start plus direct children.
Files.walk(p, 0)
Only the start path.
Since Java 8. Links are not followed by default, so a link is reported as itself rather than entered.
Library declarations
Java
public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
Walk the tree, turn each path into a relative name with forward slashes, and sort.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WalkProjectTree {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path util = Files.createDirectories(dir.resolve("src/util"));
Files.write(dir.resolve("readme.md"), new byte[0]);
Files.write(dir.resolve("src/main.java"), new byte[0]);
Files.write(util.resolve("helper.java"), new byte[0]);
List<String> paths;
try (Stream<Path> tree = Files.walk(dir)) {
paths = tree.map(p -> dir.relativize(p).toString().replace('\\', '/'))
.map(s -> s.isEmpty() ? "." : s)
.sorted()
.collect(Collectors.toList());
}
paths.forEach(System.out::println);
deleteTree(dir);
}
static void deleteTree(Path root) throws IOException {
List<Path> all;
try (Stream<Path> s = Files.walk(root)) {
all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
for (Path p : all) {
Files.delete(p);
}
}
}
Output
Run with java WalkProjectTree. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
A straight chain. The tree is the temp folder, a, a/b, and a/b/c: four paths at depths 0 to 3.
Depth 0 is the start only. Each extra level of maxDepth adds one folder of the chain.
No limit.Integer.MAX_VALUE is what the one-argument walk uses, so all four paths are found.
Example 3 — Add Up the Size of All .log Files
Find every .log file at any depth, list them sorted, and sum their sizes.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WalkLogSize {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path logs = Files.createDirectory(dir.resolve("logs"));
Files.write(dir.resolve("a.log"), new byte[10]);
Files.write(logs.resolve("b.log"), new byte[20]);
Files.write(logs.resolve("c.txt"), new byte[5]);
List<Path> found;
try (Stream<Path> tree = Files.walk(dir)) {
found = tree.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".log"))
.sorted()
.collect(Collectors.toList());
}
long total = 0;
for (Path p : found) {
System.out.println(dir.relativize(p).toString().replace('\\', '/'));
total += Files.size(p);
}
System.out.println("Total log bytes: " + total);
deleteTree(dir);
}
static void deleteTree(Path root) throws IOException {
List<Path> all;
try (Stream<Path> s = Files.walk(root)) {
all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
for (Path p : all) {
Files.delete(p);
}
}
}
Output
Run with java WalkLogSize. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
a.log
logs/b.log
Total log bytes: 30
How It Works
Exact sizes.new byte[10] writes ten zero bytes, so each file has a known size.
Two filters. Only regular files whose names end in .log pass; c.txt is skipped.
Sum after the stream.Files.size throws a checked exception, so it runs in a normal loop rather than inside a lambda: 10 + 20 = 30.
Frequently Asked Questions
try (Stream<Path> s = Files.walk(dir)) { s.filter(Files::isRegularFile)... } on Java 8+, or Files.walkFileTree on Java 7.
Yes, the start path is always the first element.
Depth-first: a folder comes before its contents, but siblings are in no particular order.
An error occurred while walking, often a folder you may not read. Stream operations cannot throw checked exceptions, so the IOException is wrapped.
Not by default. Pass FileVisitOption.FOLLOW_LINKS to enter linked folders; loops are then detected.