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

SimpleFileVisitor: Default Implementations

Extending SimpleFileVisitor to selectively override only the methods needed for custom traversal logic.

SimpleFileVisitor: Default Implementations

What you'll learn: How to extend SimpleFileVisitor to selectively override only the methods you need for custom file tree traversal logic.

The Problem with FileVisitor

When you implement the FileVisitor interface directly, you must provide implementations for all four of its methods: preVisitDirectory, visitFile, visitFileFailed, and postVisitDirectory. But what if you only need to customize one or two of these behaviors?

Enter SimpleFileVisitor

SimpleFileVisitor is a convenience class that provides sensible default implementations for all FileVisitor methods. It acts as an adapter, allowing you to extend it and override only the methods relevant to your specific traversal needs.

The default implementations:

  • preVisitDirectory: Returns CONTINUE (proceed into the directory)
  • visitFile: Returns CONTINUE (move to next file)
  • postVisitDirectory: Returns CONTINUE (move to next sibling)
  • visitFileFailed: Rethrows the IOException (fail fast)

Why This Matters

Think of SimpleFileVisitor as a template with reasonable defaults. Instead of building a complete house from scratch, you're renovating only the rooms you care about while keeping the rest as-is.

For example, if you only want to collect all .txt files, you'd extend SimpleFileVisitor and override just visitFile:

class TextFileFinder extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        if (file.toString().endsWith(".txt")) {
            System.out.println("Found: " + file);
        }
        return FileVisitResult.CONTINUE;
    }
}

The other three methods automatically use the sensible defaults from SimpleFileVisitor, saving you boilerplate code.

Key Takeaway: Extend SimpleFileVisitor instead of implementing FileVisitor directly to avoid boilerplate—override only the traversal methods you need while inheriting sensible default behavior for the rest.