Registering Paths with WatchService
What you'll learn: How to subscribe a directory to a WatchService so it can monitor specific file system events.
The Core Idea
Creating a WatchService instance is only the first step—it won't actually watch anything until you register directories with it. Think of it like subscribing to a newsletter: the service exists, but you need to explicitly tell it which topics (directories) you want to hear about and what kinds of updates (events) interest you.
You register a directory using the Path.register() method, specifying which event types you want to monitor.
How Path Registration Works
The Path interface provides a register() method that takes two arguments:
- The WatchService instance you created earlier
- One or more event types you want to watch for
The standard event types are defined in StandardWatchEventKinds:
ENTRY_CREATE- a new file/directory was createdENTRY_DELETE- a file/directory was deletedENTRY_MODIFY- a file's contents or metadata changed
Path dir = Paths.get("C:/myFolder");
WatchKey key = dir.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY);
The register() method returns a WatchKey, which acts as a token representing this registration. You'll use this key later to retrieve events.
Important Limitations
- You can only register directories, not individual files
- The registration is not recursive—subdirectories won't be monitored unless you register them separately
- You can register the same directory multiple times with different event types
Key Takeaway: Use Path.register(watchService, eventTypes...) to subscribe a directory for monitoring, receiving a WatchKey that represents this registration and will be used to retrieve events later.