Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
Visit directory contents in Java: Files.list for direct children, Files.walk and find for whole trees, glob and regex patterns with PathMatcher, filtered DirectoryStreams, walkFileTree with SimpleFileVisitor, and recipes for copying and deleting directory trees safely.
kvi5hnuCode Sprout team member9 min readOn this page
Many programs need to look at what's in a directory: find all source files in a project, add up the size of a folder, copy a tree of files, or clean up old logs. Files offers two styles for that. Stream-based methods (list, walk and find) fit nicely into stream pipelines. The visitor-based walkFileTree gives fine-grained control, including over errors. Glob patterns help with filtering in both.
Listing a directory
Files.list(dir) returns a Stream<Path> of the entries directly inside a directory, without entering subdirectories:
try (Stream<Path> entries = Files.list(dir)) {
entries.filter(Files::isRegularFile).forEach(System.out::println);
}
The directory is read lazily, so huge directories are no problem. Reading a directory holds an operating system resource, so always close the stream with try-with-resources. The entries come in no particular order. Sort them if order matters. The special entries . and .. aren't included.
Walking a tree
Files.walk(start) returns all descendants of a directory, including the start directory itself, in depth-first order: when the walk reaches a directory, it enters it before continuing with the directory's siblings.
try (Stream<Path> entries = Files.walk(root)) {
List<Path> javaFiles = entries.filter(p -> p.toString().endsWith(".java")).toList();
}
Files.walk(start, maxDepth) limits the depth. Depth 0 is just the start, and depth 1 is like list plus the start. By default, symbolic links aren't followed. Pass FileVisitOption.FOLLOW_LINKS to follow them, and the walk then detects cycles and reports them with a FileSystemLoopException.
If the walk hits a directory it can't read, the stream throws an UncheckedIOException and the whole walk ends. If you need to skip unreadable parts instead, use walkFileTree (below).
find
If your filter depends on file attributes, such as type, size or modification time, use Files.find instead. Its predicate receives the path and the BasicFileAttributes the walk has already read, which saves a separate system call per file:
try (Stream<Path> big = Files.find(root, Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && attrs.size() > 1_000_000)) {
...
}
Copying a tree
Because walk yields parents before children, copying a tree is a matter of mirroring each path under the target:
try (Stream<Path> entries = Files.walk(source)) {
for (Path p : entries.toList()) {
Path q = target.resolve(source.relativize(p).toString());
if (Files.isDirectory(p)) Files.createDirectories(q);
else Files.copy(p, q);
}
}
The toString() in resolve lets the code work even if source and target are in different file systems, such as copying out of a ZIP file system. Looping over toList() instead of using forEach avoids the awkward wrapping of IOException in a lambda.
Deleting a tree is the opposite problem: children must be deleted before their parents. Either sort the walked paths in reverse order, as earlier demos did, or use a visitor's postVisitDirectory, shown below.
Glob patterns
To select files by name, a glob is often more convenient than a regular expression. Glob syntax is the familiar shell-style wildcard notation:
| Pattern | Matches | Example |
|---|---|---|
* | zero or more characters within one name | *.java: Java files in the current directory |
** | zero or more characters, crossing directory boundaries | **/*.java: Java files in any subdirectory |
? | exactly one character | ????.java: Java files with four-character names |
[...] | one character from a set; ranges with -, negation with ! | Test[0-9A-F].java |
{a,b} | one of the alternatives | *.{java,class} |
\ | escapes a special character | *\**: names containing * |
To use a glob, get a PathMatcher from the file system. The string starts with the syntax, glob: or regex::
PathMatcher javaSource = FileSystems.getDefault().getPathMatcher("glob:**/*.java");
List<Path> sources = walkedPaths.stream().filter(javaSource::matches).toList();
A matcher checks the whole path you give it, so think about what you pass in:
**/*.javarequires at least one/, so it doesn't matchMain.javadirectly in the starting directory.**.java, or{*.java,**/*.java}, matches both.- If you walk with an absolute start, every path is absolute. A pattern like
src/**then won't match, because the path begins with/home/.... Match againstroot.relativize(path)instead, as the demo does.
On Windows, backslashes in glob patterns need double escaping, once for the glob syntax and once for the Java string: "C:\\\\Users\\\\*". Forward slashes avoid that.
Directory streams
Files.newDirectoryStream(dir) is the older, iterator-based way to list a directory. A DirectoryStream<Path> is Iterable, not a java.util.stream.Stream, so you use it in an enhanced for loop. It accepts a glob directly:
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.{md,txt}")) {
for (Path entry : entries) ...
}
Like list, it visits only direct children, in no particular order, and must be closed. An overload takes a DirectoryStream.Filter<Path> for arbitrary conditions.
walkFileTree and FileVisitor
Files.walkFileTree(start, visitor) walks a tree and calls methods of a FileVisitor<Path> at each step:
| Method | Called |
|---|---|
preVisitDirectory(Path dir, BasicFileAttributes attrs) | before a directory's entries are visited |
visitFile(Path file, BasicFileAttributes attrs) | for each non-directory entry |
postVisitDirectory(Path dir, IOException exc) | after all entries of a directory; exc is non-null if iterating the directory failed |
visitFileFailed(Path file, IOException exc) | when a file or directory can't be read or opened |
Each method returns a FileVisitResult that steers the walk:
CONTINUEgoes on to the next entry.SKIP_SUBTREE(frompreVisitDirectory) skips this directory's entries.SKIP_SIBLINGSskips the remaining entries of the current directory.TERMINATEends the walk.
If a visitor method throws an exception, the walk stops and walkFileTree throws it.
SimpleFileVisitor implements all four methods with defaults: continue, but rethrow any exception passed to visitFileFailed or postVisitDirectory. Extend it and override what you need. To walk past unreadable directories, override visitFileFailed to return CONTINUE or SKIP_SUBTREE instead of rethrowing.
walkFileTree already reads each entry's attributes to tell files from directories, and passes them to preVisitDirectory and visitFile at no extra cost.
The classic use is deleting a tree, where the directory must be removed after its contents:
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) throw e;
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
walkFileTree doesn't follow symbolic links by default, so deleting a tree this way removes links but never what they point to. That's exactly what you want.
A complete example
The demo builds a small project-like tree in a temporary directory, explores it in several ways and then deletes it with a visitor. All listings are sorted and relative to the root, so the output is the same on every run.
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.*;
import java.util.stream.*;
public class Solution {
static Path root;
static String rel(Path p) {
String s = root.relativize(p).toString();
return s.isEmpty() ? "." : s;
}
public static void main(String[] args) throws IOException {
root = Files.createTempDirectory("walkdemo");
for (String name : List.of("src/main/App.java", "src/main/Util.java", "src/test/AppTest.java",
"docs/guide.md", "docs/img/logo.png", "build/App.class", "README.md", "Main.java"))
Files.writeString(Files.createDirectories(root.resolve(name).getParent()).resolve(Path.of(name).getFileName()),
"x".repeat(name.length()));
// list: direct children only, lazily; order unspecified, so sort
try (Stream<Path> entries = Files.list(root)) {
System.out.println("list: " + entries.map(Solution::rel).sorted().toList());
}
// walk: all descendants, depth first; optional maximum depth
try (Stream<Path> entries = Files.walk(root)) {
System.out.println("walk count: " + entries.count());
}
try (Stream<Path> entries = Files.walk(root, 2)) {
System.out.println("walk depth 2: " + entries.map(Solution::rel).sorted().toList());
}
// find: filter with the attributes that the walk already has
try (Stream<Path> entries = Files.find(root, Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && attrs.size() > 15)) {
System.out.println("files over 15 bytes: " + entries.map(Solution::rel).sorted().toList());
}
// glob patterns with a PathMatcher, applied to relative paths
PathMatcher anyDepth = FileSystems.getDefault().getPathMatcher("glob:**/*.java");
PathMatcher topLevel = FileSystems.getDefault().getPathMatcher("glob:*.java");
PathMatcher eitherKind = FileSystems.getDefault().getPathMatcher("glob:**.{java,class}");
PathMatcher regex = FileSystems.getDefault().getPathMatcher("regex:.*Test\\.java");
try (Stream<Path> entries = Files.walk(root)) {
List<Path> rels = entries.map(root::relativize).toList();
System.out.println("**/*.java: " + rels.stream().filter(anyDepth::matches).map(Path::toString).sorted().toList());
System.out.println("*.java: " + rels.stream().filter(topLevel::matches).map(Path::toString).sorted().toList());
System.out.println("**.{java,class}: " + rels.stream().filter(eitherKind::matches).count() + " files");
System.out.println("regex: " + rels.stream().filter(regex::matches).map(Path::toString).toList());
}
// a directory stream with a glob filter
try (DirectoryStream<Path> entries = Files.newDirectoryStream(root.resolve("docs"), "*.{md,txt}")) {
var names = new ArrayList<String>();
for (Path entry : entries) names.add(entry.getFileName().toString());
System.out.println("docs/*.{md,txt}: " + names);
}
// walkFileTree: print directories, skip "build"
var dirs = new ArrayList<String>();
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (dir.getFileName().toString().equals("build")) return FileVisitResult.SKIP_SUBTREE;
dirs.add(rel(dir));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
return FileVisitResult.SKIP_SUBTREE; // keep going past unreadable entries
}
});
Collections.sort(dirs);
System.out.println("directories except build: " + dirs);
// copying a tree with walk
Path target = Files.createTempDirectory("walkcopy");
try (Stream<Path> entries = Files.walk(root.resolve("src"))) {
for (Path p : entries.toList()) {
Path q = target.resolve(root.resolve("src").relativize(p).toString());
if (Files.isDirectory(p)) Files.createDirectories(q);
else Files.copy(p, q);
}
}
try (Stream<Path> entries = Files.walk(target)) {
System.out.println("copied files: " + entries.filter(Files::isRegularFile).count());
}
// deleting trees with a visitor: files first, then the emptied directory
for (Path tree : List.of(root, target)) {
Files.walkFileTree(tree, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) throw e;
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
System.out.println("trees deleted: " + (Files.notExists(root) && Files.notExists(target)));
}
}
list: [Main.java, README.md, build, docs, src]
walk count: 15
walk depth 2: [., Main.java, README.md, build, build/App.class, docs, docs/guide.md, docs/img, src, src/main, src/test]
files over 15 bytes: [docs/img/logo.png, src/main/App.java, src/main/Util.java, src/test/AppTest.java]
**/*.java: [src/main/App.java, src/main/Util.java, src/test/AppTest.java]
*.java: [Main.java]
**.{java,class}: 5 files
regex: [src/test/AppTest.java]
docs/*.{md,txt}: [guide.md]
directories except build: [., docs, docs/img, src, src/main, src/test]
copied files: 3
trees deleted: true
Common questions
How do I compute the total size of a directory?
try (Stream<Path> s = Files.walk(dir)) { long total = s.filter(Files::isRegularFile).mapToLong(p -> { try { return Files.size(p); } catch (IOException e) { throw new UncheckedIOException(e); } }).sum(); }. Files.find with a predicate on attrs.isRegularFile() avoids reading the attributes twice, but it still needs a separate size call. A SimpleFileVisitor that adds attrs.size() in visitFile is the most efficient way, since the attributes come for free.
How do I find files changed in the last 24 hours?
Files.find(dir, Integer.MAX_VALUE, (p, attrs) -> attrs.isRegularFile() && attrs.lastModifiedTime().toInstant().isAfter(Instant.now().minus(Duration.ofHours(24)))).
Why does Files.walk stop with an AccessDeniedException?
A directory in the tree is unreadable, for example a system folder on Windows or another user's directory on Linux. The stream-based walk cannot skip it. Use walkFileTree and return CONTINUE from visitFileFailed.
Is the order of Files.list alphabetical?
No; it is whatever order the file system returns, which differs between systems and can change. Sort explicitly: list.sorted() sorts by path, and sorted(Comparator.comparing(p -> p.getFileName().toString(), String.CASE_INSENSITIVE_ORDER)) sorts by name the way file managers often do.
Can a WatchService watch a directory tree?
Not recursively. Register every subdirectory yourself, typically during a walkFileTree, and register new subdirectories as ENTRY_CREATE events report them. Events can also be dropped under load, reported as OVERFLOW, after which you should rescan.
Glob or regular expression?
Globs are shorter for file names (*.{png,jpg}) and familiar to users. Regular expressions are more powerful, for example for "names with a date in them". Both work through PathMatcher.
API reference
java.nio.file.Files
| Method | Description |
|---|---|
static Stream<Path> list(Path dir) | the entries of a directory, lazily; close the stream |
static Stream<Path> walk(Path start, FileVisitOption... options), walk(Path start, int maxDepth, FileVisitOption... options) | all descendants, depth first |
static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options) | descendants that match, filtered with their attributes |
static DirectoryStream<Path> newDirectoryStream(Path dir), newDirectoryStream(Path dir, String glob), newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) | an iterable over directory entries |
static Path walkFileTree(Path start, FileVisitor<? super Path> visitor), walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) | walks a tree, calling the visitor |
java.nio.file.FileSystem and java.nio.file.PathMatcher
| Method | Description |
|---|---|
PathMatcher getPathMatcher(String syntaxAndPattern) | a matcher for "glob:..." or "regex:..." |
boolean matches(Path path) | whether the whole path matches |
java.nio.file.FileVisitor<T> (and SimpleFileVisitor<T>, which continues by default and rethrows exceptions)
| Method | Description |
|---|---|
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) | before entering a directory |
FileVisitResult visitFile(T file, BasicFileAttributes attrs) | for each file |
FileVisitResult postVisitDirectory(T dir, IOException exc) | after a directory's entries |
FileVisitResult visitFileFailed(T file, IOException exc) | when an entry can't be visited |
java.nio.file.FileVisitResult: CONTINUE, SKIP_SUBTREE, SKIP_SIBLINGS, TERMINATE.
Summary
Files.liststreams the direct children of a directory.Files.walkstreams all descendants depth-first, with an optional maximum depth. Close both streams.Files.findfilters with attributes the walk has already read. Entry order is unspecified, so sort when needed.- Glob patterns (
*,**,?,[...],{...}) select names. Use them through aPathMatcher, against relative paths, and remember that**/*.javaneeds a directory level. newDirectoryStreamiterates over a directory, optionally with a glob.walkFileTreewith aSimpleFileVisitorcontrols the walk withCONTINUE,SKIP_SUBTREE,SKIP_SIBLINGSandTERMINATE, can skip unreadable entries, and deletes trees cleanly inpostVisitDirectory.
Practice Questions
What's the difference between Files.list(dir) and Files.walk(dir)?
list returns only the direct entries of dir. walk returns dir itself and all its descendants at every depth, depth first.
Why doesn't glob:**/*.java match Main.java at the root of your walk, and how do you fix it?
**/ requires the path to contain at least one directory separator, and the relative path Main.java has none. Use glob:**.java, which matches across directories and also matches a bare name, or glob:{*.java,**/*.java}.
How would you find all files larger than 10 MB under /data, efficiently?
try (var s = Files.find(Path.of("/data"), Integer.MAX_VALUE, (p, a) -> a.isRegularFile() && a.size() > 10_000_000)) { ... }. The attributes come from the walk itself, so there's no extra Files.size call per file.
Your Files.walk over a home directory dies with an AccessDeniedException deep inside. How can you walk past unreadable directories?
Use Files.walkFileTree with a SimpleFileVisitor that overrides visitFileFailed to return FileVisitResult.SKIP_SUBTREE or CONTINUE instead of rethrowing, and handles a non-null exception in postVisitDirectory the same way.
In a FileVisitor, how do you skip every directory named node_modules?
In preVisitDirectory, return FileVisitResult.SKIP_SUBTREE when dir.getFileName().toString().equals("node_modules"), and CONTINUE otherwise. The walk then never enters those directories.
Previous: Java Files: Copying, Moving, Deleting and Reading File Attributes
Next: Java Memory-Mapped Files: FileChannel.map and Performance
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.