WatchService Recursive Directory Tree

Register every existing subdirectory up front and re-register on ENTRY_CREATE of a directory, because WatchService never watches new folders by itself.

JavaCli Tooling

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.TimeUnit;

public class RecursiveTreeWatcher {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path root = Files.createTempDirectory("tree-watch");
        try (WatchService watcher = root.getFileSystem().newWatchService()) {
            root.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

            // create the subdirectory after registering the root: its ENTRY_CREATE gets captured
            Path topic = root.resolve("topic");
            Files.createDirectories(topic);

            WatchKey key = watcher.poll(1, TimeUnit.SECONDS);
            if (key == null) {
                throw new IllegalStateException("no events captured");
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                Path created = root.resolve(((WatchEvent<Path>) event).context());
                System.out.println(event.kind() + ": " + created);
                // re-register a directory when its ENTRY_CREATE arrives:
                // WatchService never watches new directories on its own; without this their events never arrive
                if (Files.isDirectory(created)) {
                    created.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
                }
            }
            key.reset();

            // topic is registered now: file events inside it arrive too
            Files.writeString(root.resolve("a.txt"), "root file");
            Files.writeString(topic.resolve("b.txt"), "nested file");

            while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    Path dir = (Path) key.watchable();
                    Path child = dir.resolve(((WatchEvent<Path>) event).context());
                    System.out.println(event.kind() + ": " + child);
                }
                key.reset();
            }
        }
    }
}

How the snippet works

Structurally, expect the class RecursiveTreeWatcher and nothing else.

Iteration happens inside for (WatchEvent<?> event : key.pollEvents()) — everything outside it runs once. The try-with-resources form guarantees each declared resource is closed even when the body throws. The failure path is explicit — IllegalStateException is raised when the guard condition holds.

Key statements

throw new IllegalStateException("no events captured");

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
The code throws `IllegalStateException`. Handle it at the call site or let it propagate deliberately.
How do you run WatchService Recursive Directory Tree?
This is a complete program, not a library excerpt — execution starts at the top.