CodeGym /Courses /JAVA 25 SELF /FileVisitor — file system traversal and recursive operati...

FileVisitor — file system traversal and recursive operations

JAVA 25 SELF
Level 39, Lesson 3
Available

1. Introduction

Let’s recall a traversal example using Files.walk():

Path start = Paths.get("my-folder");
try (Stream<Path> stream = Files.walk(start)) {
    stream.forEach(System.out::println);
}

This works great if you just need to walk files and directories and do something with them. But what if the task is more complex?

  • You need to recursively delete a directory along with all files and subdirectories (not only if it is empty).
  • You need to recursively copy or move a directory.
  • You need to gather statistics (for example, compute the total size of all files, group files by extension).
  • You need to handle errors (for example, if some directory is inaccessible, you don’t want everything to crash).

In such cases the Stream API is less convenient: you end up sprinkling try-catch blocks into lambdas, worrying about traversal order (for example, deleting files before directories), and the code becomes hard to read.

For these tasks, the file tree traversal mechanism using FileVisitor was designed.

2. The FileVisitor interface: how it works

The FileVisitor<T> interface is an “event handler” that receives notifications about every file and directory visited during file system traversal.

When you call Files.walkFileTree(start, visitor), Java starts traversing the tree from the specified path and at each step calls the corresponding method of your FileVisitor.

Main methods of the FileVisitor interface

Here is what the interface looks like:

public interface FileVisitor<T> {
    FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) throws IOException;
    FileVisitResult visitFile(T file, BasicFileAttributes attrs) throws IOException;
    FileVisitResult visitFileFailed(T file, IOException exc) throws IOException;
    FileVisitResult postVisitDirectory(T dir, IOException exc) throws IOException;
}
  • preVisitDirectory — called before entering a directory.
  • visitFile — called for each file.
  • visitFileFailed — called if access to a file failed.
  • postVisitDirectory — called after leaving a directory (that is, after all its files and subdirectories have been processed).

Each of these methods returns a value of type FileVisitResult, which determines how to proceed with the traversal:

  • FileVisitResult.CONTINUE — continue the traversal.
  • FileVisitResult.SKIP_SUBTREE — skip the current directory and everything in it.
  • FileVisitResult.SKIP_SIBLINGS — skip the remaining siblings (files and directories at this level).
  • FileVisitResult.TERMINATE — stop the traversal completely.

The SimpleFileVisitor class

Implementing all four methods every time is tedious, especially if you only need one or two. That’s why Java has a convenient adapter class SimpleFileVisitor: it already implements all methods with “default” behavior (simply CONTINUE), and you can override only what you need.

Example:

import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class MyVisitor extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("File: " + file);
        return FileVisitResult.CONTINUE;
    }
}

3. Using Files.walkFileTree: a basic example

Example 1: Print all files and directories

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class TreePrinter {
    public static void main(String[] args) throws IOException {
        Path start = Paths.get("my-folder");

        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                System.out.println("Directory: " + dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                System.out.println("  File: " + file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Output:

Directory: my-folder
  File: my-folder/file1.txt
  File: my-folder/file2.txt
Directory: my-folder/subdir
  File: my-folder/subdir/nested.txt

As you can see, the traversal is depth-first: first we enter a directory, then process its files, then move on to subdirectories.

4. Example: recursive directory deletion

One of the most common tasks: delete a directory along with all its contents. If you try to delete a directory using Files.delete(path) while it’s not empty, you’ll get an exception. You must delete all files and subdirectories first, and only then the directory itself.

Here’s how to do it with FileVisitor:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class RecursiveDelete {
    public static void main(String[] args) throws IOException {
        Path dirToDelete = Paths.get("test-folder");

        Files.walkFileTree(dirToDelete, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file); // delete file
                System.out.println("Deleted file: " + file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir); // delete directory after deleting everything inside
                System.out.println("Deleted directory: " + dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Important:
Directory deletion happens in postVisitDirectory, i.e., after everything inside has been deleted. If you tried to delete a directory before deleting the files inside, you’d get an error.

5. Example: calculating the total size of all files in a directory

Now let’s write a FileVisitor that sums the size of all files in a directory and its subdirectories.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class DirectorySizeCalculator {
    private static long totalSize = 0;

    public static void main(String[] args) throws IOException {
        Path start = Paths.get("my-folder");

        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                totalSize += attrs.size();
                return FileVisitResult.CONTINUE;
            }
        });

        System.out.println("Total size: " + totalSize + " bytes");
    }
}

Note:
We use the totalSize field to accumulate the size. In real applications it’s better to avoid static fields and pass variables via objects, but this keeps the example simple.

6. Example: searching files by pattern (extension) with FileVisitor

Suppose we need to find all .txt files in a directory and its subdirectories and print their list.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class TxtFileFinder {
    public static void main(String[] args) throws IOException {
        Path start = Paths.get("my-folder");

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

If you want to collect the found files, you can use a list:

import java.util.ArrayList;
import java.util.List;

// inside main:
List<Path> txtFiles = new ArrayList<>();
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        if (file.getFileName().toString().endsWith(".txt")) {
            txtFiles.add(file);
        }
        return FileVisitResult.CONTINUE;
    }
});
System.out.println("Total found: " + txtFiles.size());

7. Error handling and traversal particulars

What if a file or directory is inaccessible?

Sometimes during traversal you encounter files or directories that are inaccessible (for example, you lack permissions, or a file is locked by another process). In this case, the visitFileFailed method will be called.

Example:

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
    System.err.println("File access error: " + file + " (" + exc + ")");
    return FileVisitResult.CONTINUE; // continue traversal despite the error
}

If you want to stop traversal on error, return TERMINATE.

How to skip a directory completely?

If you don’t want to enter a specific directory (for example, .git or node_modules), you can return SKIP_SUBTREE in the preVisitDirectory method:

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
    if (dir.getFileName().toString().equals("node_modules")) {
        return FileVisitResult.SKIP_SUBTREE; // do not enter this directory or its subdirectories
    }
    return FileVisitResult.CONTINUE;
}

8. Practice: implement your own FileVisitor

Let’s implement a FileVisitor that:

  • Finds all files with the .java extension in a directory and its subdirectories,
  • Counts how many there are,
  • Computes their total size.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class JavaFilesStats {
    public static void main(String[] args) throws IOException {
        Path start = Paths.get("src"); // for example, the project's source code

        class JavaFileVisitor extends SimpleFileVisitor<Path> {
            int count = 0;
            long totalSize = 0;

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.getFileName().toString().endsWith(".java")) {
                    count++;
                    totalSize += attrs.size();
                    System.out.println("Found .java file: " + file);
                }
                return FileVisitResult.CONTINUE;
            }
        }

        JavaFileVisitor visitor = new JavaFileVisitor();
        Files.walkFileTree(start, visitor);

        System.out.println("Total .java files: " + visitor.count);
        System.out.println("Total size: " + visitor.totalSize + " bytes");
    }
}

9. Common mistakes when using FileVisitor

Error No. 1: trying to delete a directory before deleting the files inside. If you call Files.delete(dir) in preVisitDirectory, you’ll get an exception — you must delete all files and subdirectories first, and only then the directory itself (do this in postVisitDirectory).

Error No. 2: forgetting to handle access errors. If you don’t override visitFileFailed, the program may terminate unexpectedly when it encounters a protected file. It’s better to print the error explicitly and continue traversal.

Error No. 3: expecting the “hide file” operation to work the same on all OSes. On Linux and macOS, a hidden file starts with a dot (.gitignore), while on Windows it’s controlled by a special attribute. Don’t confuse these approaches.

Error No. 4: using static fields to accumulate results in multithreaded applications. If you run several traversals in parallel, static fields will cause confusion. Prefer instance fields (or a local class, as in the example above).

Error No. 5: forgetting to close resources when working with streams inside FileVisitor. If your FileVisitor reads/writes files, use try-with-resources to avoid leaks.

1
Task
JAVA 25 SELF, level 39, lesson 3
Locked
Research Assistant: collecting project notes
Research Assistant: collecting project notes
1
Task
JAVA 25 SELF, level 39, lesson 3
Locked
Digital Cleaner: Irreversible Project Deletion
Digital Cleaner: Irreversible Project Deletion
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION