Java Files walk() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, Files.walk(start) returns a Stream<Path> of start itself and everything below it, visited depth-first. Each folder appears before its contents, but siblings come in no particular order.

An overload takes a maxDepth to limit how deep it goes, and FileVisitOption.FOLLOW_LINKS to follow symbolic links. Like all directory streams, close it with try-with-resources.

A static method of the final utility class java.nio.file.Files, available since Java 8. Call it on the class name, as in Files.walk(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Unlimited depth, or a maximum depth and options:

Java
try (Stream<Path> tree = Files.walk(root)) { ... }
try (Stream<Path> top = Files.walk(root, 1)) { ... }                 // root + children
Files.walk(root, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS);
CallWhat it does
Files.walk(p)Whole tree, start included.
Files.walk(p, 1)Start plus direct children.
Files.walk(p, 0)Only the start path.

Since Java 8. Links are not followed by default, so a link is reported as itself rather than entered.

Library declarations
Java
public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException

Parameters

ParameterDescription
startWhere the walk begins.
maxDepthHow many levels to descend; 0 means only start.
optionsOptionally FOLLOW_LINKS.

Return Value

Return ValueDescription
Stream<Path>Every visited path, each resolved against start.

Compare with Similar Methods

Tree tools:

MethodHow it differs
find()Walk plus a filter on attributes.
walkFileTree()Java 7 visitor; skip folders, handle errors.
list()One level only.

Java Examples

Example 1 — Print Every Path in a Small Project

Walk the tree, turn each path into a relative name with forward slashes, and sort.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class WalkProjectTree {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path util = Files.createDirectories(dir.resolve("src/util"));
        Files.write(dir.resolve("readme.md"), new byte[0]);
        Files.write(dir.resolve("src/main.java"), new byte[0]);
        Files.write(util.resolve("helper.java"), new byte[0]);
        List<String> paths;
        try (Stream<Path> tree = Files.walk(dir)) {
            paths = tree.map(p -> dir.relativize(p).toString().replace('\\', '/'))
                    .map(s -> s.isEmpty() ? "." : s)
                    .sorted()
                    .collect(Collectors.toList());
        }
        paths.forEach(System.out::println);
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Start included. The walk begins with the temp folder itself, whose relative path is empty and is printed as a dot.
  2. Portable names. relativize hides the random temp location, and replacing backslashes makes Windows output match.
  3. Sorted for a stable result. Depth-first order puts folders before contents, but siblings may come in any order; sorting the strings fixes that.
  4. Same API for cleanup. deleteTree walks again and deletes in reverse order, children before parents.

Example 2 — How maxDepth Changes the Result

Walk a chain of nested folders with different depth limits and count the paths.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class WalkMaxDepth {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.createDirectories(dir.resolve("a/b/c"));
        for (int depth : new int[] {0, 1, 2, Integer.MAX_VALUE}) {
            try (Stream<Path> s = Files.walk(dir, depth)) {
                String label = depth == Integer.MAX_VALUE ? "MAX_VALUE" : String.valueOf(depth);
                System.out.println("maxDepth " + label + " finds " + s.count());
            }
        }
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. A straight chain. The tree is the temp folder, a, a/b, and a/b/c: four paths at depths 0 to 3.
  2. Depth 0 is the start only. Each extra level of maxDepth adds one folder of the chain.
  3. No limit. Integer.MAX_VALUE is what the one-argument walk uses, so all four paths are found.

Example 3 — Add Up the Size of All .log Files

Find every .log file at any depth, list them sorted, and sum their sizes.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class WalkLogSize {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path logs = Files.createDirectory(dir.resolve("logs"));
        Files.write(dir.resolve("a.log"), new byte[10]);
        Files.write(logs.resolve("b.log"), new byte[20]);
        Files.write(logs.resolve("c.txt"), new byte[5]);
        List<Path> found;
        try (Stream<Path> tree = Files.walk(dir)) {
            found = tree.filter(Files::isRegularFile)
                    .filter(p -> p.getFileName().toString().endsWith(".log"))
                    .sorted()
                    .collect(Collectors.toList());
        }
        long total = 0;
        for (Path p : found) {
            System.out.println(dir.relativize(p).toString().replace('\\', '/'));
            total += Files.size(p);
        }
        System.out.println("Total log bytes: " + total);
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Exact sizes. new byte[10] writes ten zero bytes, so each file has a known size.
  2. Two filters. Only regular files whose names end in .log pass; c.txt is skipped.
  3. Sum after the stream. Files.size throws a checked exception, so it runs in a normal loop rather than inside a lambda: 10 + 20 = 30.

Frequently Asked Questions

try (Stream<Path> s = Files.walk(dir)) { s.filter(Files::isRegularFile)... } on Java 8+, or Files.walkFileTree on Java 7.
Yes, the start path is always the first element.
Depth-first: a folder comes before its contents, but siblings are in no particular order.
An error occurred while walking, often a folder you may not read. Stream operations cannot throw checked exceptions, so the IOException is wrapped.
Not by default. Pass FileVisitOption.FOLLOW_LINKS to enter linked folders; loops are then detected.

Next: Files.walkFileTree()

Visit every file and folder in a tree with a FileVisitor that can skip, stop, or handle errors.

walkFileTree() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful