Skip Subtree While Walking Files

Prune large subtrees during Files.walkFileTree by returning SKIP_SUBTREE from preVisitDirectory, so dependency caches and hidden files never enter the walk.

JavaData Integrity

Code

snippet
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 PrunedWalk {

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("project-");
        Files.writeString(root.resolve("app.log"), "main log line");
        Files.createDirectories(root.resolve("node_modules/pkg"));
        Files.writeString(root.resolve("node_modules/pkg/index.js"), "dep code");
        Files.writeString(root.resolve(".cache"), "hidden scratch");

        long[] counted = {0};
        // Returning SKIP_SUBTREE from preVisitDirectory makes the walker skip the whole subtree
        Files.walkFileTree(root, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                if (dir.getFileName().toString().equals("node_modules")) {
                    System.out.println("skip subtree: node_modules");
                    return FileVisitResult.SKIP_SUBTREE;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.getFileName().toString().startsWith(".")) {
                    System.out.println("skip hidden file: " + root.relativize(file));
                    return FileVisitResult.CONTINUE;
                }
                counted[0] += attrs.size();
                System.out.println("visited: " + root.relativize(file));
                return FileVisitResult.CONTINUE;
            }
        });
        System.out.println("counted bytes: " + counted[0]);
    }
}

What the code does

Under the hood: the class PrunedWalk and the functions preVisitDirectory and visitFile.

Caveats

  • Copy, run: the standard library answers every call in the file.

Applying it

Entry signature: public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)

The file announces its steps in the output: skip subtree: node_modules, skip hidden file:, visited:.

The entry point wires preVisitDirectory and visitFile together — run it once and the whole demo flows.

Statements that matter

counted[0] += attrs.size();

Interactive Tools for This Topic

FAQ

What does Skip Subtree While Walking Files print when run?
Invoke the file as-is — the `skip subtree: node_modules`, `skip hidden file:`, `visited:` prefixes identify which step printed each line.