Java Reference
In-Depth Information
To start monitoring a folder, create a
WatchService
that you can use to poll for
changes. After the
WatchService
has been created, register the
WatchService
with a path. A path symbolizes a folder in the file system. When the
WatchService
is registered with the path, you define the kinds of events you want to monitor (see
Table 8-2
).
WatchEvent
Description
OVERFLOW
An event that has overflown (ignore)
A directory or file was created
ENTRY_CREATE
A directory or file has been deleted
ENTRY_DELETE
A directory or file has been modified
ENTRY_MODIFY
After registering the
WatchService
with the path, you can then “poll” the
WatchService
for event occurrences. By calling
the watchService.poll()
method, you will wait for a file/folder event to occur on that path. Using the
watchService.poll(int timeout, Timeunit timeUnit)
will wait un-
til the specified timeout is reached before continuing. If the
watchService
receives
an event, or if the allowed time has passed, then it will continue execution. If there
were no events and the timeout was reached, the
WatchKey
object returned by the
watchService.poll(int timeout)
will be null; otherwise, the
WatchKey
object returned will contain the relevant information for the event that has occurred.
Because many events can occur at the same time (say, for example, moving an en-
tire folder or pasting a bunch of files into a folder), the
WatchKey
might contain more
than one event. You can use the
watchKey
to obtain all the events that are associated
with that key by calling the
watchKey.pollEvents()
method.
The
watchKey.pollEvents()
call will return a list of
watchEvents
that
can be iterated over. Each
watchEvent
contains information on the actual file or
folder to which the event refers (for example, an entire subfolder could have been
moved or deleted), and the event type (add, edit, delete). Only those events that were
registered on the
WatchService
will be processed. The event types you can register
are listed in
Table 8-2
.
Once an event has been processed, it is important to call the
EventKey.reset()
. The reset will return a Boolean value determining whether the
WatchKey
is still valid. A
WatchKey
becomes invalid if it is cancelled or if its ori-