135. Watching paths

Watching paths for changes is just one of the thread-safe goals that can be accomplished via the JDK 7 NIO.2, low-level WatchService API.

In a nutshell, a path can be watched for changes by following two major steps:

  1. Register a folder (or folders) to be watched for different kinds of event types.
  2. When a registered event type is detected by WatchService, it is handled in a separate thread, so the watch service is not blocked.

At the API level, the starting point is the WatchService interface. This interface comes in different flavors for different file/operating systems.

This interface works hand-in-hand with two main classes. Together, they provide a convenient approach that you can implement to add watching capabilities to a certain context (for example, to the filesystem):

  • Watchable: Any object that implements this interface is a watchable object, and so it can be watched for changes (for example, Path)
  • StandardWatchEventKinds: This class defines the standard event types (these are the event types that we can register for notifications:
    • ENTRY_CREATE: Directory entry created
    • ENTRY_DELETE: Directory entry deleted
    • ENTRY_MODIFY: Directory entry modified; what is considered as a modification is somewhat platform-specific, but actually modifying the content of a file should always trigger this event type
    • OVERFLOW: A special event to indicate that events may have been lost or discarded

WatchService is known as the watcher, and we say that the watcher watches watchables. In the following examples, WatchService will be created through the FileSystem class and will watch the registered Path.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset