Quick revision
The short answer
The JDK uses the visitor pattern in Files.walkFileTree, where a FileVisitor receives a call for each element of a directory tree, and also in the annotation processing API, whose ElementVisitor visits program elements, while bytecode libraries such as ASM are built around ClassVisitor and MethodVisitor. Files.walkFileTree traverses the tree and calls preVisitDirectory, visitFile, visitFileFailed and postVisitDirectory on the visitor, and each method returns a FileVisitResult, CONTINUE, SKIP_SUBTREE, SKIP_SIBLINGS or TERMINATE, to control the walk. SimpleFileVisitor gives default implementations of all four, so we override only the ones we need.
What to remember
In this answer, we saw that the visitor pattern separates an operation from the structure it walks, and that Files.walkFileTree applies it to directory trees: it traverses depth first and calls preVisitDirectory, visitFile, visitFileFailed and postVisitDirectory on a FileVisitor, whose FileVisitResult return values CONTINUE, SKIP_SUBTREE, SKIP_SIBLINGS and TERMINATE steer the walk. SimpleFileVisitor supplies defaults so we override only what we need, and the same pattern appears in ElementVisitor for annotation processing and in ASM's ClassVisitor.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The JDK uses the visitor pattern in Files.walkFileTree, where a FileVisitor receives a call for each element of a directory tree, and also in the annotation processing API, whose ElementVisitor visits program elements, while bytecode libraries such as ASM are built around ClassVisitor and MethodVisitor. Files.walkFileTree traverses the tree and calls preVisitDirectory, visitFile, visitFileFailed and postVisitDirectory on the visitor, and each method returns a FileVisitResult, CONTINUE, SKIP_SUBTREE, SKIP_SIBLINGS or TERMINATE, to control the walk. SimpleFileVisitor gives default implementations of all four, so we override only the ones we need.
Why this question is asked
Walking a directory tree looks easy until we meet the details: directories we cannot read, symbolic links that loop, work that must happen after a directory's contents are done, such as deleting it, and the wish to stop early once we find what we were looking for. Files.walkFileTree handles all of that, and its design is a clear example of the visitor pattern, which otherwise feels abstract to many developers. Interviewers ask about it because it lets us explain a pattern through an API we can use in production code. In this answer, we will recap the visitor pattern, follow walkFileTree through a small tree, write visitors that count, delete and search, and look at the other JDK and library visitors.
1A Quick Recap of the Visitor Pattern
The visitor pattern separates an operation from the structure it works on. The structure, a tree of objects of a few different kinds, knows how to traverse itself, and for each element it calls a method on a visitor object, a different method for each kind of element. The visitor holds the operation: counting, printing, deleting, searching. To add a new operation, we write a new visitor; the structure and its traversal stay unchanged.
In the classic form, elements have an accept(visitor) method that calls back visitor.visitX(this), a technique called double dispatch, so the right method runs for each element type. walkFileTree uses a looser form: the traversal code itself knows whether it is at a directory or a file, and calls the matching visitor method. The intent is the same: the walk is written once, and many operations plug into it.
2How Files.walkFileTree Calls the Visitor
Files.walkFileTree(start, visitor) performs a depth-first walk. For each directory, it first calls preVisitDirectory(dir, attrs), then visits the entries inside, and after the last entry calls postVisitDirectory(dir, exception). For each regular file, and for other non-directory entries, it calls visitFile(file, attrs). If an entry cannot be read, for example because of permissions, it calls visitFileFailed(file, exception) instead. The attrs argument, BasicFileAttributes, gives size, times and type without a separate system call, which is one reason this API is efficient.
- Is the entry readable?Attributes could be readYesContinue belowNovisitFileFailed(file, exception)
- Is it a directory?Links are not followed by defaultYespreVisitDirectory(dir, attrs)NovisitFile(file, attrs)
- Result of preVisitDirectory?CONTINUE or
SKIP_SUBTREEYesVisit each entry inside, then postVisitDirectoryNoSkip its contents and its post call - Any result TERMINATE?From any methodYesStop the whole walkNoMove on to the next entry
4 steps in order. Play them, or step through them one at a time.
Notice that postVisitDirectory for docs/img comes before the post for docs: every directory is finished only after everything inside it. The order of entries within a directory is not guaranteed, it depends on the file system, so code must not rely on a.txt coming before img.
3Steering the Walk With FileVisitResult
Each visitor method returns a FileVisitResult, which is how the visitor controls the traversal. CONTINUE goes on as normal. SKIP_SUBTREE, meaningful from preVisitDirectory, skips that directory's contents, and its postVisitDirectory is not called. SKIP_SIBLINGS skips the remaining entries of the current directory. TERMINATE stops the walk immediately, and walkFileTree returns.
Here are two visitors that use those results. The first skips the build output folders while counting Java files. The second searches for a file and stops as soon as it is found, which on a large tree can save minutes.
The one-element arrays are a common trick, since anonymous classes can only capture effectively final variables; a small named visitor class with fields is cleaner in production code.
4SimpleFileVisitor and the Classic Recursive Delete
FileVisitor is an interface with four methods. SimpleFileVisitor implements all of them: the three visit methods return CONTINUE, while visitFileFailed rethrows the exception, and postVisitDirectory rethrows any exception passed to it. So we override only what we need, as above. That default matters: without overriding visitFileFailed, one unreadable file ends the whole walk with an exception.
Deleting a directory tree shows why postVisitDirectory exists. A directory can only be deleted when it is empty, so we delete files in visitFile and the directory itself in postVisitDirectory, after all its contents are gone.
By default walkFileTree does not follow symbolic links, so a link is visited as a file and deleting it removes the link, not its target. To follow links we pass FileVisitOption.FOLLOW_LINKS, and then the walk detects cycles and reports them through visitFileFailed with a FileSystemLoopException. For simple cases, Files.walk returns a lazy Stream<Path> instead, which is handy for filtering, but it offers no pre and post hooks and must be closed with try-with-resources.
5Other Visitors in the JDK and Libraries
The annotation processing API in javax.lang.model has ElementVisitor, with methods such as visitType, visitExecutable and visitVariable for classes, methods and fields, and TypeVisitor for types; base classes such as SimpleElementVisitor and ElementScanner play the same role as SimpleFileVisitor. Annotation processors use them to walk the program elements the compiler gives them. The newer Class-File API, final in JDK 24, models class files with sealed types that are processed with pattern matching rather than visitors.
ASM, the bytecode library used inside many frameworks for proxies and instrumentation, is built around visitors: a ClassReader walks a class file and calls methods on a ClassVisitor, such as visitMethod, which returns a MethodVisitor for the instructions. Chaining visitors lets a tool transform a class while it is being read, which is the visitor pattern used for efficiency as well as structure.
| API | Structure walked | Visitor and base class |
|---|---|---|
Files.walkFileTree | Directory tree | FileVisitor, SimpleFileVisitor |
javax.lang.model.element | Program elements in annotation processing | ElementVisitor, SimpleElementVisitor, ElementScanner |
javax.lang.model.type | Types such as arrays and generics | TypeVisitor, SimpleTypeVisitor |
| ASM | Class file bytecode | ClassVisitor, MethodVisitor |
6Follow-up questions
What is the difference between Files.walk and Files.walkFileTree?
Files.walk returns a lazy Stream<Path> of every entry, which is convenient for filtering and mapping with stream operations, but it has no hook after a directory's contents and stops with an UncheckedIOException on errors. walkFileTree gives pre and post directory callbacks, per-entry error handling and control over skipping, which suits deletes, copies and robust scans.
Why does the visitor pattern make adding operations easy but adding element types hard?
Each operation is one visitor class, so a new operation is one new class. But every visitor has one method per element type, so a new element type means adding a method to every visitor. That is why the pattern suits stable structures, like file trees or Java's element kinds, with many operations.
Does walkFileTree visit the start path itself?
Yes. If the start path is a directory, preVisitDirectory is called for it first and postVisitDirectory last; if it is a file, visitFile is called once for it. The maxDepth argument of the longer overload limits how deep the walk goes, where 0 visits only the start path.
7Conclusion
In this answer, we saw that the visitor pattern separates an operation from the structure it walks, and that Files.walkFileTree applies it to directory trees: it traverses depth first and calls preVisitDirectory, visitFile, visitFileFailed and postVisitDirectory on a FileVisitor, whose FileVisitResult return values CONTINUE, SKIP_SUBTREE, SKIP_SIBLINGS and TERMINATE steer the walk. SimpleFileVisitor supplies defaults so we override only what we need, and the same pattern appears in ElementVisitor for annotation processing and in ASM's ClassVisitor.
Open with
The visitor pattern separates an operation from the structure it works on: the structure handles traversal and calls a method on a visitor for each element, so a new operation is just a new visitor.
Then, if they want more
The clearest JDK example is Files.walkFileTree. I pass it a start path and a FileVisitor, and it does a depth-first walk. For each directory it calls preVisitDirectory before the contents and postVisitDirectory after them, for each file it calls visitFile with its basic attributes, and if an entry cannot be read it calls visitFileFailed with the exception.
Each method returns a FileVisitResult to control the walk: CONTINUE, SKIP_SUBTREE to skip a directory's contents, which is how I would skip target or .git, SKIP_SIBLINGS to skip the rest of the current directory, and TERMINATE to stop, for example once a search finds its file.
SimpleFileVisitor implements all four methods, continuing by default and rethrowing errors, so I only override what I need. The classic use is recursive delete: delete files in visitFile and the directory in postVisitDirectory, because by then it is empty. Links are not followed unless I pass FOLLOW_LINKS, and then loops are reported through visitFileFailed.
Other examples are the annotation processing API, where ElementVisitor visits types, methods and fields, and bytecode libraries like ASM, where a ClassReader drives a ClassVisitor and MethodVisitor.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 24
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Where does the JDK use the visitor pattern? Explain how Files.walkFileTree with a...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/f8f28a5db6/