Traversing directories with Files.walk, walkFileTree and DirectoryStream
Java offers five ways to go through a directory: Files.list and DirectoryStream for one level, Files.walk and Files.find for a whole tree as a lazy stream, and Files.walkFileTree for full control with a visitor. This page explains how they work underneath, runs each on the same small project tree, and shows leaked directory handles, copying and deleting trees, link loops and the cost of extra attribute calls.
Contents
How directory traversal works
An operating system lists a directory one entry at a time: a program opens the directory, reads entries until there are none left, and closes it. Each open directory holds a file descriptor, a limited per-process resource. Java's DirectoryStream
wraps oneFiles.list in aDirectoryStream .Stream andFiles.walk go depth first. They keep a stack of open directory streams, one for each level between the root and the current entry, and read each entry's basic attributes to know whether it is a directory to descend into.Files.find uses the same walker, but instead of producing a stream it calls methods on yourFiles.walkFileTree before a directory, for each file, after a directory and on errors.FileVisitor
Two consequences follow. First, entries come in whatever order the file system stores them, which is not alphabetical and differs between machines, so sort when the order matters. Second, the stream methods hold open directories until they are closed, so they belong in try-with-resources.
| Method | Since | Depth | Returns | Best for |
|---|---|---|---|---|
Files.newDirectoryStream(dir, glob) | Java 7 | One level | DirectoryStream<Path>Iterable | Glob filters; very large directories |
Files.list(dir) | Java 8 | One level | Stream<Path> | Simple listings with stream operations |
Files.walk(root, depth) | Java 8 | Whole tree | Stream<Path> | Searching and aggregating |
Files.find(root, depth, filter) | Java 8 | Whole tree | Stream<Path> | Filters on size, dates or type |
Files.walkFileTree(root, visitor) | Java 7 | Whole tree | Callbacks | Skipping subtrees, per-file error handling, copying and deleting trees |
A helper class creates the same small project in a temporary directory for most programs: three Java sources, a README, and two compiled class files under build
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
// Builds the same small project tree for every example
final class Tree {
private Tree() {
}
static Path create() throws IOException {
Path root = Files.createTempDirectory("walk-demo");
String[][] files = {
{"src/main/App.java", "class App {}"},
{"src/main/util/Strings.java", "class Strings { /* helpers */ }"},
{"src/test/AppTest.java", "class AppTest {}"},
{"docs/README.md", "# Demo project"},
{"build/App.class", "0123456789".repeat(100)},
{"build/util/Strings.class", "0123456789".repeat(50)},
};
for (String[] f : files) {
Path p = root.resolve(f[0]);
Files.createDirectories(p.getParent());
Files.writeString(p, f[1]);
}
return root;
}
}
Files.walk and Files.find
Files.walk(root)Stream<Path>
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WalkBasics {
static String ext(Path p) {
String name = p.getFileName().toString();
return name.substring(name.lastIndexOf('.') + 1);
}
public static void main(String[] args) throws IOException {
Path root = Tree.create();
// Files.walk: every file and directory below root, depth first, lazily
try (Stream<Path> all = Files.walk(root)) {
System.out.println("walk (sorted):");
all.map(root::relativize).map(Path::toString).filter(s -> !s.isEmpty()).sorted()
.forEach(s -> System.out.println(" " + s));
}
// maxDepth 1 is the same as listing the top level
try (Stream<Path> top = Files.walk(root, 1)) {
System.out.println("depth 1: " + top.skip(1).map(root::relativize).map(Path::toString)
.sorted().toList());
}
// Count and size per extension
try (Stream<Path> files = Files.walk(root)) {
Map<String, Long> bytes = files.filter(Files::isRegularFile)
.collect(Collectors.groupingBy(WalkBasics::ext, TreeMap::new,
Collectors.summingLong(p -> p.toFile().length())));
System.out.println("bytes per extension: " + bytes);
}
// Files.find gets the attributes for free, so size filters need no extra calls
try (Stream<Path> big = Files.find(root, Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && attrs.size() > 400)) {
System.out.println("files over 400 bytes: " + big.map(root::relativize)
.map(Path::toString).sorted().toList());
}
Cleanup.deleteTree(root);
}
}
Output:
walk (sorted):
build
build/App.class
build/util
build/util/Strings.class
docs
docs/README.md
src
src/main
src/main/App.java
src/main/util
src/main/util/Strings.java
src/test
src/test/AppTest.java
depth 1: [build, docs, src]
bytes per extension: {class=1500, java=59, md=14}
files over 400 bytes: [build/App.class, build/util/Strings.class]
- The full walk lists 13 entries below the root, directories included. It is sorted only to make the output stable.
limits the depth, so it is the top level plus the root itself, whichFiles.walk(root, 1) removes. That is the same asskip(1) .Files.list(root)- Grouping by extension and summing sizes takes one pipeline. The three Java files total 12 + 31 + 16 = 59 bytes, and the two class files 1,500.
passes each entry'sFiles.find to the filter. The walker has read them already, so checking the size costs nothing extra, unlike callingBasicFileAttributes inside aFiles.size filter. The speed section below measures the difference.Files.walk
Lazy walks and leaked directory handles
Because the walk is lazy, it only reads as far as the stream pipeline asks. And because it holds directories open, forgetting to close it leaks them. The program builds a tree of 200 directories with 50 files each, 10,201 entries with the root, and shows both effects. It counts open descriptors through /proc/self/fd
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class LazyAndLeaks {
// Linux and macOS expose a process's open file descriptors as a directory
static long openDescriptors() throws IOException {
Path fds = Path.of("/proc/self/fd");
if (!Files.isDirectory(fds)) {
return -1;
}
try (Stream<Path> s = Files.list(fds)) {
return s.count();
}
}
public static void main(String[] args) throws IOException {
// A tree of 200 directories with 50 files each
Path root = Files.createTempDirectory("lazy");
for (int d = 0; d < 200; d++) {
Path dir = Files.createDirectory(root.resolve(String.format("dir-%03d", d)));
for (int f = 0; f < 50; f++) {
Files.writeString(dir.resolve("file-" + f + ".txt"), "x");
}
}
// The stream is lazy: findFirst stops the walk as soon as it has a match
AtomicInteger seen = new AtomicInteger();
try (Stream<Path> s = Files.walk(root)) {
Optional<Path> first = s.peek(p -> seen.incrementAndGet())
.filter(p -> p.getFileName().toString().equals("file-3.txt"))
.findFirst();
System.out.println("findFirst found a match: " + first.isPresent()
+ ", entries visited: " + seen.get() + " of 10,201");
}
seen.set(0);
try (Stream<Path> s = Files.walk(root)) {
long count = s.peek(p -> seen.incrementAndGet())
.filter(p -> p.getFileName().toString().equals("file-3.txt")).count();
System.out.println("count of matches: " + count + ", entries visited: " + seen.get());
}
// Each unclosed stream keeps a directory open
long before = openDescriptors();
for (int i = 0; i < 100; i++) {
Stream<Path> leaked = Files.list(root.resolve(String.format("dir-%03d", i)));
leaked.iterator().next(); // used, but never closed
}
long after = openDescriptors();
System.out.println("open descriptors before: " + before + ", after 100 unclosed "
+ "Files.list calls: +" + (after - before));
long beforeClosed = openDescriptors();
for (int i = 0; i < 100; i++) {
try (Stream<Path> s = Files.list(root.resolve(String.format("dir-%03d", i)))) {
s.iterator().next();
}
}
System.out.println("after 100 closed Files.list calls: +"
+ (openDescriptors() - beforeClosed));
try (Stream<Path> s = Files.walk(root)) {
s.sorted(java.util.Comparator.reverseOrder()).forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new java.io.UncheckedIOException(e);
}
});
}
}
}
Output (on Linux):
findFirst found a match: true, entries visited: 45 of 10,201
count of matches: 200, entries visited: 10201
open descriptors before: 8, after 100 unclosed Files.list calls: +200
after 100 closed Files.list calls: +0
stopped the walk after 45 of 10,201 entries: the root, the first directory the walker opened, and the files in it up to the first match.findFirst had to visit all 10,201 to find the 200 matches. A search that needs one result should end withcount() orfindFirst .anyMatch- Each of the 100
streams that were used but never closed left its directory open: 200 more descriptors, two per stream on this JDK. They stay open until the stream is closed or garbage collected at some unknown time. A server that does this per request eventually fails with "Too many open files"; the default limit on many Linux systems is 1,024 per process.Files.list - The same 100 calls in try-with-resources left nothing open.
walkFileTree: visitors, skipped subtrees and deleting a tree
Files.walkFileTreeFileVisitorpreVisitDirectoryvisitFilepostVisitDirectoryvisitFileFailedSimpleFileVisitorCONTINUESKIP_SUBTREESKIP_SIBLINGSTERMINATE
The CleanupvisitFilepostVisitDirectory
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
final class Cleanup {
private Cleanup() {
}
// Deletes files on the way down and each directory after its contents
static int deleteTree(Path root) throws IOException {
int[] deleted = {0};
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
deleted[0]++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) {
throw e;
}
Files.delete(dir);
deleted[0]++;
return FileVisitResult.CONTINUE;
}
});
return deleted[0];
}
}
The program prints the tree with indentation and skips buildCleanup
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class VisitorDemo {
public static void main(String[] args) throws IOException {
Path root = Tree.create();
// A visitor can skip whole subtrees, which Files.walk cannot do
StringBuilder log = new StringBuilder();
Files.walkFileTree(root, new SimpleFileVisitor<>() {
int depth = 0;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (dir.getFileName().toString().equals("build")) {
log.append(" ".repeat(depth)).append("build/ (skipped)\n");
return FileVisitResult.SKIP_SUBTREE;
}
log.append(" ".repeat(depth)).append(dir.equals(root) ? "." : dir.getFileName())
.append("/\n");
depth++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
log.append(" ".repeat(depth)).append(file.getFileName()).append('\n');
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) {
depth--;
return FileVisitResult.CONTINUE;
}
});
System.out.print(log);
System.out.println("deleted entries: " + Cleanup.deleteTree(root));
System.out.println("root still exists: " + Files.exists(root));
}
}
Output (the order of entries within a directory follows the file system and can differ on your machine):
./
src/
test/
AppTest.java
main/
util/
Strings.java
App.java
build/ (skipped)
docs/
README.md
deleted entries: 14
root still exists: false
Nothing under buildFiles.walkFiles.deletepostVisitDirectory
Copying a tree, and deleting with a stream
Copying a directory tree is the other classic visitor job: create each directory in preVisitDirectoryvisitFilerelativizeresolvebuild
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Comparator;
import java.util.stream.Stream;
public class CopyTree {
// Copies source into target, keeping the relative layout and file times
static int copyTree(Path source, Path target) throws IOException {
int[] copied = {0};
Files.walkFileTree(source, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
if (dir.getFileName().toString().equals("build")) {
return FileVisitResult.SKIP_SUBTREE; // do not copy build output
}
Files.createDirectories(target.resolve(source.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.copy(file, target.resolve(source.relativize(file)),
StandardCopyOption.COPY_ATTRIBUTES);
copied[0]++;
return FileVisitResult.CONTINUE;
}
});
return copied[0];
}
public static void main(String[] args) throws IOException {
Path project = Tree.create();
Path backup = Files.createTempDirectory("backup").resolve("project-copy");
Path original = project.resolve("docs/README.md");
Files.setLastModifiedTime(original,
FileTime.from(Instant.parse("2026-01-15T10:30:00.123456789Z")));
System.out.println("files copied: " + copyTree(project, backup));
try (Stream<Path> s = Files.walk(backup)) {
s.map(p -> backup.relativize(p).toString()).filter(n -> !n.isEmpty()).sorted()
.forEach(n -> System.out.println(" " + n));
}
Path copy = backup.resolve("docs/README.md");
System.out.println("same content: " + (Files.mismatch(original, copy) == -1));
System.out.println("original time: " + Files.getLastModifiedTime(original));
System.out.println("copy time: " + Files.getLastModifiedTime(copy));
// Deleting with a stream: sort deepest first, so children go before parents
try (Stream<Path> s = Files.walk(backup.getParent())) {
long deleted = s.sorted(Comparator.reverseOrder()).peek(p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).count();
System.out.println("deleted with walk + reverse sort: " + deleted + " entries");
}
System.out.println("deleted with a visitor: " + Cleanup.deleteTree(project) + " entries");
}
}
Output:
files copied: 4
docs
docs/README.md
src
src/main
src/main/App.java
src/main/util
src/main/util/Strings.java
src/test
src/test/AppTest.java
same content: true
original time: 2026-01-15T10:30:00.123456789Z
copy time: 2026-01-15T10:30:00.123456Z
deleted with walk + reverse sort: 11 entries
deleted with a visitor: 14 entries
- Four files were copied and the layout below the root is the same, without
.build kept the modification time, but on JDK 21 on Linux only to the microsecond:COPY_ATTRIBUTES became.123456789 . The JDK 25 runtime on the same machine kept all nine digits. Tools that compare times exactly to decide whether a file changed should compare with.123456 or allow a small difference.toMillis()- Deleting with a stream works by sorting the paths in reverse order, so that
comes beforea/b/c ; the delete removed 11 entries, the copy's 10 plus the temporary parent. Sorting has to collect every path in memory first, and ana/b must be wrapped to leave the lambda. The visitor version needs neither.IOException
Globs, symbolic links and errors
Files.newDirectoryStream(dir, glob)*.{java,kt}**/*.javaPathMatchersrc/main
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
public class GlobAndLinks {
public static void main(String[] args) throws IOException {
Path root = Tree.create();
Path main = root.resolve("src/main");
// DirectoryStream: one level only, filtered by a glob pattern
List<String> javaFiles = new ArrayList<>();
try (DirectoryStream<Path> ds = Files.newDirectoryStream(main, "*.{java,kt}")) {
ds.forEach(p -> javaFiles.add(p.getFileName().toString()));
}
System.out.println("glob *.{java,kt} in src/main: " + javaFiles);
// A glob that crosses directories needs a PathMatcher and a walk
var matcher = root.getFileSystem().getPathMatcher("glob:**/*.java");
try (Stream<Path> s = Files.walk(root)) {
List<String> all = new ArrayList<>(s.filter(matcher::matches)
.map(p -> root.relativize(p).toString()).toList());
Collections.sort(all);
System.out.println("glob:**/*.java anywhere: " + all);
}
// A symbolic link that points back to an ancestor creates a cycle
Files.createSymbolicLink(main.resolve("loop"), root);
try (Stream<Path> s = Files.walk(root)) {
System.out.println("walk without FOLLOW_LINKS: " + s.count() + " entries");
}
try (Stream<Path> s = Files.walk(root, FileVisitOption.FOLLOW_LINKS)) {
s.forEach(p -> { });
} catch (UncheckedIOException e) {
System.out.println("walk with FOLLOW_LINKS: "
+ (e.getCause() instanceof FileSystemLoopException
? "FileSystemLoopException" : e.getCause()));
}
// A visitor gets the same problem as a call, and can carry on
int[] counts = new int[2];
Files.walkFileTree(root, java.util.EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, new java.nio.file.SimpleFileVisitor<>() {
@Override
public java.nio.file.FileVisitResult visitFile(Path f,
java.nio.file.attribute.BasicFileAttributes a) {
counts[0]++;
return java.nio.file.FileVisitResult.CONTINUE;
}
@Override
public java.nio.file.FileVisitResult visitFileFailed(Path f,
IOException e) {
counts[1]++;
System.out.println("visitFileFailed: " + root.relativize(f) + " ("
+ e.getClass().getSimpleName() + "), continuing");
return java.nio.file.FileVisitResult.CONTINUE;
}
});
System.out.println("visitor with FOLLOW_LINKS: " + counts[0] + " files, "
+ counts[1] + " failure");
Files.delete(main.resolve("loop"));
Cleanup.deleteTree(root);
}
}
Output:
glob *.{java,kt} in src/main: [App.java]
glob:**/*.java anywhere: [src/main/App.java, src/main/util/Strings.java, src/test/AppTest.java]
walk without FOLLOW_LINKS: 15 entries
walk with FOLLOW_LINKS: FileSystemLoopException
visitFileFailed: src/main/loop (FileSystemLoopException), continuing
visitor with FOLLOW_LINKS: 6 files, 1 failure
- The one-level listing finds only
;App.java is in theStrings.java subdirectory.util crosses directory boundaries, so the matcher finds all three Java files. A single** stops at* ./- By default, walks do not follow symbolic links. The link is reported as one entry, 15 instead of 14, and not entered.
- With
, the walker notices that the link leads to a directory it is already inside and reportsFOLLOW_LINKS .FileSystemLoopException wraps it in anFiles.walk , because streams cannot throw checked exceptions, and the whole walk ends there.UncheckedIOException - The visitor received the same error in
, printed it and returnedvisitFileFailed , so it still visited all 6 files. The same applies to a directory without read permission: a stream walk stops, a visitor can log it and carry on.CONTINUE
| Pattern | Matches |
|---|---|
* | Any characters within one name, not / |
** | Any characters, crossing directories |
? | Exactly one character |
{java,kt} | Either alternative |
[a-c] | One character from the set |
getPathMatcher"regex:..."
Speed: where the extra calls go
The traversal itself is cheap; extra attribute calls per entry are what make a walk slow. The program creates 30,000 small files in 300 directories and sums their sizes four ways, best of 5 runs each.
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Stream;
public class WalkSpeed {
interface Scan {
long totalBytes(Path root) throws IOException;
}
static long walkWithSize(Path root) throws IOException {
try (Stream<Path> s = Files.walk(root)) {
return s.filter(Files::isRegularFile).mapToLong(p -> p.toFile().length()).sum();
}
}
static long find(Path root) throws IOException {
long[] total = {0};
try (Stream<Path> s = Files.find(root, Integer.MAX_VALUE, (p, a) -> {
if (a.isRegularFile()) {
total[0] += a.size();
}
return false;
})) {
s.count();
}
return total[0];
}
static long visitor(Path root) throws IOException {
long[] total = {0};
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
total[0] += attrs.size();
return FileVisitResult.CONTINUE;
}
});
return total[0];
}
static long listFiles(File dir) {
long total = 0;
File[] children = dir.listFiles();
if (children != null) {
for (File f : children) {
total += f.isDirectory() ? listFiles(f) : f.length();
}
}
return total;
}
static void measure(String label, Path root, Scan scan) throws IOException {
long best = Long.MAX_VALUE;
long total = 0;
for (int i = 0; i < 5; i++) {
long start = System.nanoTime();
total = scan.totalBytes(root);
best = Math.min(best, System.nanoTime() - start);
}
System.out.printf("%-36s %4d ms %,d bytes%n", label, best / 1000000, total);
}
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("speed");
for (int d = 0; d < 300; d++) {
Path dir = Files.createDirectories(root.resolve("pkg" + d % 10 + "/sub" + d));
for (int f = 0; f < 100; f++) {
Files.writeString(dir.resolve("F" + f + ".java"), "x".repeat(f));
}
}
System.out.println("30,000 files in 300 directories, best of 5");
visitor(root); // warm-up
measure("Files.walk + isRegularFile + length", root, WalkSpeed::walkWithSize);
measure("Files.find with attributes", root, WalkSpeed::find);
measure("Files.walkFileTree visitor", root, WalkSpeed::visitor);
measure("recursive File.listFiles", root, r -> listFiles(r.toFile()));
Cleanup.deleteTree(root);
}
}
Output (rough comparison on a 2-CPU Linux VM, JDK 21; absolute times will differ on yours):
30,000 files in 300 directories, best of 5
Files.walk + isRegularFile + length 65 ms 1,485,000 bytes
Files.find with attributes 38 ms 1,485,000 bytes
Files.walkFileTree visitor 38 ms 1,485,000 bytes
recursive File.listFiles 71 ms 1,485,000 bytes
- All four found the same 1,485,000 bytes: 300 directories times 0 + 1 + ... + 99 bytes.
followed byFiles.walk andisRegularFile was the slowest, because it asked the file system twice more for every entry after the walker had already read the attributes.length andFiles.find used the attributes the walker had read and were the fastest, close to each other.walkFileTree- Recursive
was in the same range as the walk with extra calls, faster in some runs and slower in others. It also asks the file system separately for each entry, and it builds a full array for every directory.File.listFiles
Which method to use
| Task | Use |
|---|---|
| List one directory | Files.list(dir) |
| One directory filtered by name pattern | Files.newDirectoryStream(dir, "*.log") |
| Search a tree for names | Files.walkPathMatcherfindFirst |
| Search by size, date or type | Files.find |
Skip subtrees such as build.git | walkFileTreeSKIP_SUBTREE |
| Copy or delete a tree | walkFileTreeSimpleFileVisitor |
| Keep going past unreadable entries | walkFileTreevisitFileFailedCONTINUE |
| Follow symbolic links | FOLLOW_LINKSFileSystemLoopException |
For the operations on single files and their attributes, see