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.
Code
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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do you run WatchService Directory Events?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.