WatchService Directory Events

Watch a directory for ENTRY_CREATE, ENTRY_MODIFY, and ENTRY_DELETE with WatchService, polling keys with a timeout and resetting them after each drain.

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 InboxWatcher {

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

            // 注册之后再产生变更,事件才会被捕获
            Path note = inbox.resolve("note.txt");
            Files.writeString(note, "hello");
            Files.writeString(note, "hello again");
            Files.deleteIfExists(note);

            // poll 带超时:不永久阻塞;处理完必须 reset,否则后续事件不再投递
            WatchKey key;
            while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    System.out.println(event.kind() + ": " + event.context());
                }
                key.reset();
            }
        }
    }
}

Inside the snippet

The working surface is the class InboxWatcher — everything else is wiring.

Iteration happens inside while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) — everything outside it runs once. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Key statements

Path inbox = Files.createTempDirectory("inbox");
Files.writeString(note, "hello again");
Path note = inbox.resolve("note.txt");

Interactive Tools for This Topic

FAQ

How do you run WatchService Directory Events?
Run the file on its own; every call resolves against the standard surface it already imports.