Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
startPathThe folder to start from; it is included in the stream too.
maxDepthintOptional depth: 1 means only the folder's own contents.
optionsFileVisitOption...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.java

Counting .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
2

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.