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.
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 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
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 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.