Java Files.walk, find and walkFileTree
Traverse a tree using a stream, a metadata predicate, or a visitor.
A simple example
Files.walk, find and walkFileTree
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
JDK 21 declarations (5)
public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOExceptionpublic static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOExceptionpublic static Stream<Path> walk(Path start, FileVisitOption... options) throws IOExceptionpublic static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOExceptionpublic static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind receipts inside monthly folders
A club treasurer organizes receipts into month folders. A top-level list misses those receipts, so count regular files across the tree and locate the CSV files within two levels of the starting folder.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path month = Files.createDirectory(desk.resolve("March"));
Files.createFile(month.resolve("dues.csv"));
Files.createFile(desk.resolve("notes.txt"));
try (var all = Files.walk(desk)) { System.out.println(all.filter(Files::isRegularFile).count()); }
try (var csv = Files.find(desk, 2, (p, a) -> a.isRegularFile() && p.toString().endsWith(".csv"))) {
System.out.println(csv.map(Path::getFileName).toList());
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
2 [dues.csv]
The starting folder is at depth zero. The receipt inside March is at depth two.
Visit each file for a stock audit
An inventory tool needs to process files as it encounters them. Use a visitor to report a small test manifest and show where a larger program could decide to continue or stop.
import java.nio.file.*;
import java.nio.file.attribute.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Files.createFile(desk.resolve("stock.csv"));
Files.walkFileTree(desk, new SimpleFileVisitor<Path>() {
@Override public FileVisitResult visitFile(Path p, BasicFileAttributes a) {
System.out.println(p.getFileName());
return FileVisitResult.CONTINUE;
}
});
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
stock.csv
The callback runs on the file and returns the instruction to continue traversal.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
The start path participates in the traversal. Close streams and choose a depth limit that includes the files you intend to find.