Sub topic 14
Walking directory trees
This chapter covers three ways to visit every file under a directory: Files.walk, Files.find and Files.walkFileTree. It assumes you know Path, Files, try-with-resources and Stream. It also assumes you know how to list one directory, which the directories chapter covers.
Choosing a traversal tool
A directory tree is a directory that contains files and other directories, to any depth. Listing one directory shows only its direct children. A walk descends into every subdirectory as well.
| Tool | Style | Best for |
|---|---|---|
| `Files.walk` | Lazy `Stream<Path>` | Filtering and collecting paths |
| `Files.find` | Lazy `Stream<Path>` with a predicate that receives attributes | Filtering by size, type or time without extra file system calls |
| `Files.walkFileTree` | Callbacks on a `FileVisitor` | Skipping subtrees, handling errors per entry, deleting or copying trees |
Streaming with Files.walk
Files.walk(start) returns a stream of every path under start, depth-first. The start path itself is the first element. The stream is lazy, so directories are read as you consume it. It holds open directory handles, which means you must close it.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class FindTextFiles {
public static void main(String[] args) throws IOException {
Path root = Path.of(".");
try (Stream<Path> paths = Files.walk(root)) {
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".txt"))
.forEach(System.out::println);
}
}
}Files::isRegularFile keeps ordinary files and drops directories. The extension test uses toString(). The walk guarantees no particular order, so call sorted() if you need stable output.
Limiting depth
A second argument sets the maximum depth. A depth of 0 returns only the start path. A depth of 1 returns the start and its direct children. Integer.MAX_VALUE is the default.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ShallowWalk {
public static void main(String[] args) throws IOException {
Path root = Path.of("data");
try (Stream<Path> paths = Files.walk(root, 2)) {
paths.sorted()
.forEach(p -> System.out.println("[" + root.relativize(p) + "]"));
}
}
}The first line prints [], because the relative form of the start path is empty. Skip it with filter(p -> !p.equals(root)) if that matters. This is where relativize from the path operations chapter is useful. It turns absolute or prefixed paths into names relative to the root.
Filtering with Files.find
Files.find(start, maxDepth, matcher) is a walk whose predicate receives both the path and its BasicFileAttributes. The walk has usually already read the attributes, so the predicate often needs no extra file system call. maxDepth is required.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class FindLargeFiles {
public static void main(String[] args) throws IOException {
Path root = Path.of(".");
try (Stream<Path> found = Files.find(root, Integer.MAX_VALUE,
(path, attrs) -> attrs.isRegularFile() && attrs.size() > 1_000_000)) {
found.forEach(System.out::println);
}
}
}Errors during a stream walk
Stream methods cannot throw checked exceptions. If an I/O error occurs while the stream is being consumed, for example a directory you may not read, the stream throws UncheckedIOException. Its getCause() is the original IOException. The whole walk stops. You cannot skip the unreadable directory and continue.
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class WalkWithErrors {
public static void main(String[] args) {
Path root = Path.of(".");
try (Stream<Path> paths = Files.walk(root)) {
System.out.println(paths.count());
} catch (UncheckedIOException e) {
System.out.println("Walk failed: " + e.getCause().getMessage());
} catch (IOException e) {
System.out.println("Could not open: " + e.getMessage());
}
}
}The two catch blocks cover two different moments. Files.walk itself can throw IOException when it opens the start directory. Errors found later arrive as UncheckedIOException. If you need to keep going after an error, use walkFileTree.
Symbolic links and loops
A symbolic link is a file that points to another path. By default, Files.walk, Files.find and the two-argument walkFileTree do not follow links. A link to a directory appears as one entry and is not entered.
Pass FileVisitOption.FOLLOW_LINKS to follow links. Links can form cycles, such as a link that points to its own parent. When the walk detects a cycle it reports a FileSystemLoopException. In a stream walk that arrives wrapped in UncheckedIOException. Follow links only when you need to, and expect that failure.
Control with walkFileTree
Files.walkFileTree(start, visitor) calls methods on a FileVisitor<Path> as it goes. Extend SimpleFileVisitor and override only what you need. Each method returns a FileVisitResult that tells the walk what to do next.
| Callback | Called | Typical use |
|---|---|---|
| `preVisitDirectory` | Before a directory's entries | Skip a subtree, create a matching directory |
| `visitFile` | For each non-directory entry | Process the file |
| `visitFileFailed` | When an entry cannot be read | Log and continue, or abort |
| `postVisitDirectory` | After all entries of a directory | Delete the directory, summarize |
The results are CONTINUE, TERMINATE (stop the whole walk), SKIP_SUBTREE (do not enter this directory) and SKIP_SIBLINGS (skip the remaining entries in this directory).
Skipping a subtree and surviving errors
This program lists text files but never enters a directory named .git. It also logs unreadable entries and keeps going.
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 TextFilesSkippingGit {
public static void main(String[] args) throws IOException {
Path root = Path.of(".");
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (dir.getFileName() != null && dir.getFileName().toString().equals(".git")) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.toString().endsWith(".txt")) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println("Skipping " + file + ": " + exc.getMessage());
return FileVisitResult.CONTINUE;
}
});
}
}The getFileName() != null check matters because a root path such as / has no file name.
Deleting a tree
Files.delete fails on a non-empty directory, so you must delete the files first and the directory afterwards. visitFile handles the files. postVisitDirectory runs after a directory's contents are gone, which is the right moment to remove it.
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 DeleteTree {
public static void main(String[] args) throws IOException {
Path root = Path.of("build-output");
if (!Files.exists(root)) {
return;
}
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}Because this walk does not follow links, a symbolic link is deleted as a link and its target is untouched.
Edge cases and decisions
- Always close stream walks. Forgetting the try-with-resources leaks directory handles. On a large tree this can exhaust the process's file descriptors.
- Do not modify the tree you are streaming. Files created or removed during a
Files.walkmay or may not appear. Collect paths into aListfirst if you need to change things afterwards. - Avoid sorting for deletion. Sorting a stream in reverse order deletes children before parents, but it loads every path into memory.
walkFileTreeuses constant memory for the same job. - Compare against the start path, not strings. Paths from a walk keep the prefix of
start, so a relative start gives relative results. CalltoAbsolutePath()first if you need absolute ones. - Decide how much failure you tolerate. A stream walk is simpler and fails fast. A visitor is longer and lets you decide per entry.
Exercise
You use Files.walk on a directory that contains one subdirectory your program is not allowed to read. What happens, and which tool would let you log the problem and continue with the rest of the tree?
Show answer
The stream throws UncheckedIOException, whose cause is the original IOException (an AccessDeniedException), and the walk stops. Use Files.walkFileTree with a SimpleFileVisitor that overrides visitFileFailed to log the error and return FileVisitResult.CONTINUE.
Exercise
Write the call that streams all regular files at most two levels below Path.of("logs") whose size is above 10_000 bytes, using the attributes the walk already has.
Show answer
try (Stream<Path> found = Files.find(Path.of("logs"), 2, (p, attrs) -> attrs.isRegularFile() && attrs.size() > 10_000)) { found.forEach(System.out::println); }