Course contentsShow
← Java
Lesson 2096 of 2,87041. NIO.2 and the Path APIFree lesson

Registering Paths with WatchService

Using Path.register() to subscribe a directory for monitoring with specific event types.

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:

  1. The WatchService instance you created earlier
  2. 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 created
  • ENTRY_DELETE - a file/directory was deleted
  • ENTRY_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.