Java Reference
In-Depth Information
Reset the WatchKey after Processing Events
You must reset the
WatchKey
object by calling its
reset()
method, so it may receive event notifications and be queued
to the watch service again. The
reset()
method puts the
WatchKey
into the
ready
state. The
reset()
method returns
true
if the
WatchKey
is still valid. Otherwise, it returns
false
. A
WatchKey
may become invalid if it is cancelled or its
watch service is closed.
// Reset the WatchKey
boolean isKeyValid = key.reset();
if (!isKeyValid) {
System.out.println("No longer watching " + dirToWatch);
}
Close the Watch Service
When you are done with the watch service, close it by calling its
close()
method. You will need to handle the
java.io.IOException
when you call its
close()
method.
// Close the watch service
ws.close();
■
the
WatchService
is
AutoCloseable
. If you create an object of the
WatchService
in a
try-with-resources
block, it will be automatically closed when the program exits the block.
Tip
Listing 10-20 has a complete program that watches a
C:\kishori
directory for changes. You can replace the
directory path in the
Watcher
class with the directory path that you want to watch for changes. You will need to make
changes to the watched directory, such as creating a new file and changing an existing file, after you run the
Watcher
class. The output will show the details of the events that occur on an entry in the watched directory. You may get a
different output.
Listing 10-20.
Implementing a Watch Service to Monitor Changes in a Directory
// Watcher.java
package com.jdojo.nio2;
import java.nio.file.WatchEvent.Kind;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchService;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;