FileVisitResult: Controlling Traversal Flow
What you'll learn: How to control directory tree traversal by returning specific FileVisitResult values from your FileVisitor methods.
When you implement FileVisitor methods (like those in SimpleFileVisitor), you don't just perform actions—you also tell the traversal engine what to do next. Each method must return a FileVisitResult enum value that controls the flow.
The Four Control Signals
CONTINUE
Tells the tree walker to proceed normally. "Keep going as planned—visit the next file or directory."
TERMINATE
Immediately stops the entire traversal. "I'm done—stop walking the tree completely, regardless of what's left."
SKIP_SUBTREE
Only valid in preVisitDirectory. Tells the walker to skip the current directory's contents entirely but continue with siblings. "Don't go into this folder, but keep processing other folders at this level."
SKIP_SIBLINGS
Skips remaining siblings at the current level but continues processing parent directories. "I'm done at this level—go back up and continue from there."
Practical Example
Think of it like exploring rooms in a building:
- CONTINUE: "Check the next room"
- SKIP_SUBTREE: "Don't open that closet, but check other rooms"
- SKIP_SIBLINGS: "Done with this floor, go upstairs"
- TERMINATE: "Exit the building immediately"
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.getFileName().toString().equals("secret.txt")) {
return FileVisitResult.TERMINATE; // Found it! Stop searching.
}
return FileVisitResult.CONTINUE; // Keep looking
}
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (dir.getFileName().toString().equals(".git")) {
return FileVisitResult.SKIP_SUBTREE; // Ignore version control folders
}
return FileVisitResult.CONTINUE;
}
Key Takeaway: FileVisitResult gives you fine-grained control over directory traversal—continue normally, skip directories, skip siblings, or terminate the entire walk based on your logic.