Java Files walkFileTree() Method

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

Definition

In Java, Files.walkFileTree(start, visitor) walks a directory tree depth-first and calls your visitor for each entry: preVisitDirectory before a folder's contents, visitFile for each file, postVisitDirectory after the contents, and visitFileFailed when an entry cannot be read.

Each callback returns a FileVisitResult, giving you control that streams lack. Extend SimpleFileVisitor and override only what you need. Siblings are visited in no particular order.

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

Syntax

Pass a visitor; the 4-argument overload adds options and a depth limit:

Java
Files.walkFileTree(root, visitor);
Files.walkFileTree(root, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 3, visitor);
CallWhat it does
CONTINUEKeep walking.
SKIP_SUBTREEFrom preVisitDirectory: do not enter this folder.
SKIP_SIBLINGSSkip the rest of the current folder.
TERMINATEStop the whole walk.

Since Java 7, so it also works where walk and find (Java 8) are not available.

Library declarations
Java
public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException
public static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException

Parameters

ParameterDescription
startWhere the walk begins.
options(4-argument overload) For example FOLLOW_LINKS.
maxDepth(4-argument overload) Maximum levels to visit.
visitorReceives the callbacks.

Return Value

Return ValueDescription
PathThe start path.

Compare with Similar Methods

Choosing a tree API:

MethodHow it differs
walk()Simpler stream, no skipping or error recovery.
find()Stream filtered by attributes.
delete()Used in postVisitDirectory to remove trees.

Java Examples

Example 1 — Count Folders, Files, and Bytes

An anonymous SimpleFileVisitor updates counters in two callbacks.

Java
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 WalkFileTreeCount {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path sub = Files.createDirectory(dir.resolve("sub"));
        Files.write(dir.resolve("a.txt"), new byte[3]);
        Files.write(sub.resolve("b.txt"), new byte[5]);
        Files.write(sub.resolve("c.txt"), new byte[2]);
        final long[] totals = new long[3];
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path d, BasicFileAttributes attrs) {
                totals[0]++;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                totals[1]++;
                totals[2] += attrs.size();
                return FileVisitResult.CONTINUE;
            }
        });
        System.out.println("Folders: " + totals[0] + ", files: " + totals[1] + ", bytes: " + totals[2]);
        Files.delete(sub.resolve("b.txt"));
        Files.delete(sub.resolve("c.txt"));
        Files.delete(sub);
        Files.delete(dir.resolve("a.txt"));
        Files.delete(dir);
    }
}

How It Works

  1. Override two callbacks. SimpleFileVisitor already returns CONTINUE everywhere else.
  2. Folders include the start. preVisitDirectory runs for the temp folder and for sub, giving 2.
  3. Sizes from attributes. attrs.size() gives 3 + 5 + 2 = 10 bytes. The counters live in an array because an anonymous class cannot reassign local variables.

Example 2 — Delete a Folder Tree in postVisitDirectory

Delete files as they are visited and each folder once its contents are gone.

Java
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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class WalkFileTreeDelete {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path lib = Files.createDirectories(dir.resolve("build/lib"));
        Path build = lib.getParent();
        Files.write(build.resolve("out.class"), new byte[1]);
        Files.write(lib.resolve("x.jar"), new byte[1]);
        final List<String> deleted = new ArrayList<>();
        Files.walkFileTree(build, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                deleted.add(file.getFileName().toString());
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
                if (exc != null) {
                    throw exc;
                }
                Files.delete(d);
                deleted.add(d.getFileName() + "/");
                return FileVisitResult.CONTINUE;
            }
        });
        Collections.sort(deleted);
        System.out.println("Deleted: " + deleted);
        System.out.println("build exists: " + Files.exists(build));
        Files.delete(dir);
    }
}

How It Works

  1. Files first. visitFile deletes each file the moment it is reached.
  2. Folders last. postVisitDirectory runs after a folder's contents, when it is already empty, so deleting it never fails with DirectoryNotEmptyException.
  3. Do not swallow errors. A non-null exc means listing the folder failed, so it is rethrown. The log is sorted because out.class and lib may be visited in either order.

Example 3 — Skip node_modules While Collecting Files

Return SKIP_SUBTREE for one folder name, using the 4-argument overload.

Java
import java.io.IOException;
import java.nio.file.FileVisitOption;
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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;

public class WalkFileTreeSkip {
    public static void main(String[] args) throws IOException {
        final Path dir = Files.createTempDirectory("demo");
        Files.createDirectories(dir.resolve("lib"));
        Files.createDirectories(dir.resolve("node_modules"));
        Files.write(dir.resolve("app.js"), new byte[0]);
        Files.write(dir.resolve("lib/util.js"), new byte[0]);
        Files.write(dir.resolve("node_modules/dep.js"), new byte[0]);
        final List<String> files = new ArrayList<>();
        Files.walkFileTree(dir, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path d, BasicFileAttributes attrs) {
                        boolean skip = d.getFileName().toString().equals("node_modules");
                        return skip ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                        files.add(dir.relativize(file).toString().replace('\\', '/'));
                        return FileVisitResult.CONTINUE;
                    }
                });
        Collections.sort(files);
        System.out.println("Source files: " + files);
        Files.delete(dir.resolve("node_modules/dep.js"));
        Files.delete(dir.resolve("node_modules"));
        Files.delete(dir.resolve("lib/util.js"));
        Files.delete(dir.resolve("lib"));
        Files.delete(dir.resolve("app.js"));
        Files.delete(dir);
    }
}

How It Works

  1. Decide at the door. preVisitDirectory sees each folder before entering it and returns SKIP_SUBTREE for node_modules.
  2. Never entered. dep.js is not visited at all, which is faster than filtering it out afterwards.
  3. Explicit options. No options and Integer.MAX_VALUE are what the 2-argument overload uses.

Frequently Asked Questions

Use Files.walkFileTree with a SimpleFileVisitor that deletes files in visitFile and folders in postVisitDirectory.
A FileVisitor with default methods that continue the walk and rethrow errors. Extend it and override only the callbacks you need.
Return FileVisitResult.SKIP_SUBTREE from preVisitDirectory for that folder.
Override visitFileFailed to log the error and return CONTINUE.
Files.walk (Java 8) is shorter for listings. walkFileTree (Java 7) can skip subtrees, act after a folder, and recover from errors.

Next: Files.write()

Write a byte array or a list of lines to a file in one call.

write() 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.

9 people found this page helpful