Java Reference
In-Depth Information
3. Create an array of
Kind
enumerations for the things you want to watch (in our ex-
ample we watch for files being created or modified).
4. Register the
WatchService
and the
Kind
array onto the
Path
object.
5. From then on, you wait for the watcher to notify you. A typical implementation is to
enter a
while (true)
loop calling the
WatchService
's
take()
method to get an
“event,” and interpret these to figure out “what just happened.”
Example 11-1
is a program that does just that. In addition, it starts another thread to actually
do some filesystem operations, so that you can see the Watcher Service operating.
Example 11-1. src/main/java/nio/FileWatchServiceDemo.java
public
public class
class
FileWatchServiceDemo
FileWatchServiceDemo
{
final
final static
static
String tempDirPath
=
"/tmp"
;
static
static
Thread mainRunner
;
static
static volatile
volatile
boolean
boolean
done
=
false
false
;
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Throwable
{
String tempDirPath
=
"/tmp"
;
System
.
out
.
println
(
"Starting watcher for "
+
tempDirPath
);
Path p
=
Paths
.
get
(
tempDirPath
);
WatchService watcher
=
FileSystems
.
getDefault
().
newWatchService
();
Kind
<?>[]
watchKinds
= {
ENTRY_CREATE
,
ENTRY_MODIFY
};
p
.
register
(
watcher
,
watchKinds
);
mainRunner
=
Thread
.
currentThread
();
new
new
Thread
(
new
new
DemoService
()).
start
();
while
while
(!
done
) {
WatchKey key
=
watcher
.
take
();
for
for
(
WatchEvent
<?>
e
:
key
.
pollEvents
()) {
System
.
out
.
println
(
"Saw event "
+
e
.
kind
() +
" on "
+
e
.
context
());
iif
(
e
.
context
().
toString
().
equals
(
"MyFileSema.for"
)) {
System
.
out
.
println
(
"Semaphore found, shutting down watcher"
);
done
=
true
true
;
}
}
iif
(!
key
.
reset
()) {
System
.
err
.
println
(
"Key failed to reset!"
);
}
}