Java Reference
In-Depth Information
Register the Directory with the Watch Service
You need to create a
Path
object for the directory you want to watch and invoke its
register()
method to register
it with the watch service. At the time of registration, you need to specify the kinds of events for which you want to
register your directory. The
register()
method will return a
WatchKey
object as a registration token.
// Get a Path object for C:\kishori directory to watch
Path dirToWatch = Paths.get("C:\\kishori");
// Register the dirToWatch for create, modify and delete events
WatchKey token = dirToWatch.register(ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
You can cancel the registration of a directory with the watch service using the
cancel()
method of the
WatchKey
.
When a directory is registered, its
WatchKey
is said to be in the
ready
state. You can register multiple directories with a
watch service. Note that the directory must exist at the time of registration.
Retrieve a WatchKey from the Watch Service Queue
When an event occurs on a registered directory, the
WatchKey
for that registered directory is said to be in the
signaled
state and the
WatchKey
is queued to the watch service. Another event may occur on a registered directory when its
WatchKey
is in the
signaled
state. If an event occurs on a directory while its
WatchKey
is in the
signaled
state, the event
is queued to the
WatchKey
, but the
WatchKey
itself is not re-queued to the watch service. A
WatchKey
in the
signaled
state remains in this state until its
reset()
method is called to change its state to the
ready
state.
You can use the
take()
or
poll()
method of the
WatchService
object to retrieve and remove a signaled and
queued
WatchKey
. The
take()
method waits until a
WatchKey
is available. The
poll()
method lets you specify a
timeout for the wait. Typically, an infinite loop is used to retrieve a signaled
WatchKey
.
while(true) {
// Retrieve and remove the next available WatchKey from the watch service
WatchKey key = ws.take();
}
Process the Events
Once you retrieve and remove a
WatchKey
from the watch service queue, you can retrieve and remove all pending
events for that
WatchKey
. A
WatchKey
may have more than one pending events. The
pollEvents()
method of the
WatchKey
retrieves and removes all its pending events. It returns a
List
of
WatchEvent
. Each element of the
List
represents an event on the
WatchKey
. Typically, you will need to use the
kind()
,
context()
, and
count()
methods
of the
WatchEvent
object to know the details of the event. The following snippet of code shows the typical logic for
processing an event:
while(true) {
// Retrieve and remove the next available WatchKey
WatchKey key = ws.take();
// Process all events of the WatchKey
for(WatchEvent<?> event : key.pollEvents()) {
// Process each event here
}
}