Java Reference
In-Depth Information
•
The
WatchEvent<T>
interface
•
The
WatchEvent.Kind<T>
interface
StandardWatchEventKinds
class
A
Watchable
object represents a file-system object that can be watched for changes. A
Watchable
object can be
registered with a watch service. A
Path
object is a
Watchable
object. Therefore, you can register a
Path
object with a
watch service.
A
WatchService
represents a watch service that watches registered objects for changes. When an object is
registered with a
WatchService
, the
WatchService
returns a
WatchKey
that serves as a token for the registration. In
other words, a
WatchKey
identifies the registration of an object with a
WatchService
.
A
WatchEvent
represents an event (or a repeated event) on an object registered with a watch service. Its
kind()
method returns the kind of event that occurs on the registered object. Its
context()
method returns a
Path
object
that represents the entry on which the event occurs. The
Path
object represents a relative path between the registered
directory with the watch service and the entry on which the event occurs. An event may be repeated before it is
notified. The
count()
method returns the number of times the event occurs for a specific notification. If it returns a
value greater than 1, it is a repeated event.
A
WatchEvent.Kind<T>
represents the kind of event that occurs on a registered object. The
StandardWatchEventKinds
class defines constants to represent the kind of an event.
The
StandardWatchEventKinds
class defines the following four constants to identify the kind of an event. Each
constant is of the type
WatchEvent.Kind
type. It contains the following constants:
•
The
ENTRY_CREATE
•
ENTRY_DELETE
•
ENTRY_MODIFY
•
OVERFLOW
The names of the first three constants are self-explanatory. They represent events when an entry is created,
deleted, and modified in a registered directory.
The last event kind is
OVERFLOW
, which represents a special kind of event to indicate that event may have been lost
or discarded.
The following steps are needed to watch a directory for changes:
•
•
Create a watch service.
•
Register a directory with the watch service.
•
Retrieve a watch key from the watch service queue.
•
Process the events that occur on the registered directory.
•
Reset the watch key after processing the events.
•
Close the watch service.
Create a Watch Service
Create a watch service for the file system in which you want to watch a directory for changes as follows:
WatchService ws = FileSystems.getDefault().newWatchService();