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:
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);
}
}
Output
Run with java WalkFileTreeCount. Totals do not depend on visiting order; the output is the same on Windows, macOS, and Linux.
Folders: 2, files: 3, bytes: 10
How It Works
Override two callbacks.SimpleFileVisitor already returns CONTINUE everywhere else.
Folders include the start.preVisitDirectory runs for the temp folder and for sub, giving 2.
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);
}
}
Output
Run with java WalkFileTreeDelete. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
Files first.visitFile deletes each file the moment it is reached.
Folders last.postVisitDirectory runs after a folder's contents, when it is already empty, so deleting it never fails with DirectoryNotEmptyException.
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);
}
}
Output
Run with java WalkFileTreeSkip. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
Source files: [app.js, lib/util.js]
How It Works
Decide at the door.preVisitDirectory sees each folder before entering it and returns SKIP_SUBTREE for node_modules.
Never entered. dep.js is not visited at all, which is faster than filtering it out afterwards.
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.