Files.walk()
Walks a folder and all nested folders and returns a stream of every path found.
Available since: Java 7
Syntax
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options)Parameters
| Parameter | Type | Description |
|---|---|---|
| start | Path | The folder to start from; it is included in the stream too. |
| maxDepth | int | Optional depth: 1 means only the folder's own contents. |
| options | FileVisitOption... | Optional: FOLLOW_LINKS to follow symbolic links. |
Return value
Stream<Path>A lazy stream of paths that must be closed.
Examples
The whole folder tree. Paths are shown relative to the root; replace only makes the output the same on Windows:
void main() throws IOException {
Path root = Files.createTempDirectory("demo");
Files.createDirectories(root.resolve("src/app"));
Files.writeString(root.resolve("README.md"), "hi");
Files.writeString(root.resolve("src/app/Main.java"), "class Main {}");
try (Stream<Path> paths = Files.walk(root)) {
paths.filter(p -> !p.equals(root))
.map(p -> root.relativize(p).toString().replace('\\', '/'))
.sorted()
.forEach(IO::println);
}
}Output:
README.md
src
src/app
src/app/Main.javaCounting .java files and limiting the depth:
void main() throws IOException {
Path root = Files.createTempDirectory("demo");
Files.createDirectories(root.resolve("a/b"));
Files.writeString(root.resolve("a/One.java"), "");
Files.writeString(root.resolve("a/b/Two.java"), "");
Files.writeString(root.resolve("a/b/notes.txt"), "");
try (Stream<Path> paths = Files.walk(root)) {
IO.println(paths.filter(p -> p.toString().endsWith(".java")).count());
}
try (Stream<Path> paths = Files.walk(root, 1)) {
IO.println(paths.count());
}
}Output:
2
2Notes
The walk is depth-first, and the order within a folder depends on the system — sort it yourself. The stream keeps folders open, so always use try with resources. If some folder is not accessible, the whole walk stops with UncheckedIOException. For searching by a condition there is Files.find(start, depth, (path, attrs) -> ...), and Files.list() returns just one folder's contents.
See also
- Files.list() — Returns a stream of the files and folders inside a folder (not nested). Files.walk() goes recursively.
- Path.of() — Creates a Path object — a path to a file or folder.
- Files.exists() — Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().
- try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.
In the tutorial
- Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.