Course contentsShow
← Java
Lesson 2087 of 2,87041. NIO.2 and the Path APIFree lesson

FileVisitor Interface and Its Methods

Understanding preVisitDirectory, visitFile, visitFileFailed, and postVisitDirectory callback methods.

FileVisitor Interface and Its Methods

You'll learn how the FileVisitor interface provides callback methods that let you control what happens at every stage of traversing a file tree.

The Four Callback Methods

When you walk a file tree (like with Files.walkFileTree), you need to specify what to do at each point in the journey. The FileVisitor<Path> interface defines four callback methods that act like hooks at different stages:

1. preVisitDirectory

Called before visiting a directory's contents. Think of this as "knocking on the door" before entering a folder. You can inspect the directory and decide whether to enter it or skip it entirely.

2. visitFile

Called when visiting a regular file. This is where you typically process individual files—reading, copying, or analyzing them.

3. visitFileFailed

Called when a file cannot be accessed. Maybe you lack permissions, or the file was deleted between discovery and visit. This method lets you handle errors gracefully.

4. postVisitDirectory

Called after all entries in a directory have been visited. Think of it as "closing the door behind you" when leaving a folder. Useful for cleanup or summary operations.

The Pattern

Each method receives the relevant Path and returns a FileVisitResult that controls what happens next (continue, skip siblings, skip subtree, or terminate). This gives you fine-grained control over the traversal process.

Think of FileVisitor like a tour guide protocol: you get notified before entering rooms (preVisitDirectory), when examining items (visitFile), when something goes wrong (visitFileFailed), and when leaving rooms (postVisitDirectory).

Key Takeaway:
The FileVisitor interface defines four callback methods—preVisitDirectory, visitFile, visitFileFailed, and postVisitDirectory—that let you control behavior at every stage of file tree traversal.