Library contents

Java Files.walk, find and walkFileTree

Traverse a tree using a stream, a metadata predicate, or a visitor.

A simple example

Files.walk, find and walkFileTree

  1. Start with Folder a contains b/c.txt
  2. Do this Visit descendants
  3. Result The walk reaches c.txt
Recursive traversal descends into b before discovering the file inside it.

Syntax

Java syntax
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
JDK 21 declarations (5)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Find receipts inside monthly folders

A club treasurer organizes receipts into month folders. A top-level list misses those receipts, so count regular files across the tree and locate the CSV files within two levels of the starting folder.

First output line2
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path month = Files.createDirectory(desk.resolve("March"));
            Files.createFile(month.resolve("dues.csv"));
            Files.createFile(desk.resolve("notes.txt"));
            try (var all = Files.walk(desk)) { System.out.println(all.filter(Files::isRegularFile).count()); }
            try (var csv = Files.find(desk, 2, (p, a) -> a.isRegularFile() && p.toString().endsWith(".csv"))) {
                System.out.println(csv.map(Path::getFileName).toList());
            }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
2
[dues.csv]

The starting folder is at depth zero. The receipt inside March is at depth two.

Advertisements

Visit each file for a stock audit

An inventory tool needs to process files as it encounters them. Use a visitor to report a small test manifest and show where a larger program could decide to continue or stop.

Resultstock.csv
Main.java
import java.nio.file.*;
import java.nio.file.attribute.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Files.createFile(desk.resolve("stock.csv"));
            Files.walkFileTree(desk, new SimpleFileVisitor<Path>() {
                @Override public FileVisitResult visitFile(Path p, BasicFileAttributes a) {
                    System.out.println(p.getFileName());
                    return FileVisitResult.CONTINUE;
                }
            });
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
stock.csv

The callback runs on the file and returns the instruction to continue traversal.

Inventory class submissions

A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.

Givenanna.pdf · li.pdf · team/plan.pdf
Worked result3

What to watch for

The start path participates in the traversal. Close streams and choose a depth limit that includes the files you intend to find.

Documentation for Files.walk, find and walkFileTree