- A watch service that watches registered objects
for changes and events. For example a file manager may use a watch service
to monitor a directory for changes so that it can update its display of
the list of files when files are created or deleted
Java 7 adds a new feature for
its NIO package called Watch Service API which allows applications monitoring
directories and files for change events such as creation, deletion and
modification. The Watch Service API is fairly simple to use, and relieves
programmers from using third party libraries for files change monitoring. In
this article, we’ll see how to use this API in the simplest form with a simple
demo program. All interfaces and classes in the Watch Service API can be found
in the package java.nio.file.
Step 1:
WatchService watcher = FileSystems.getDefault().newWatchService();
Step 2:
Then register this WatchService for a given directory
like the following:
Path dir = Paths.get("Path/To/Watched/Directory");
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
The register() method of the Path class takes a WatchService object and a varargs list of event types which
the application needs to get notified. The supported event types are:
·
o ENTRY_CREATE:
indicates that a directory or file is created.
o ENTRY_DELETE:
indicates that a directory or file is deleted.
o ENTRY_MODIFY:
indicates that a directory or file is modified.
o OVERFLOW:
indicates that the event might have been lost or discarded. This event is
always implicitly registered so we don’t need to explicitly specify it in
the register() method.
All these event types are
declared in the java.nio.file.StandardWatchEventKinds class.
NOTES: The Watch Service API
does not allow registering an individual file. We’ll get a java.nio.file.NotDirectoryException if trying to do so.
Final Step: write an infinite loop
to repeatedly poll the events fired by the watcher and process the events
accordingly.
import java.nio.file.Path;
import java.nio.file.Paths;
import
java.nio.file.WatchEvent;
import
java.nio.file.WatchKey;
import
java.nio.file.WatchService;
import java.util.List;
import static
java.nio.file.StandardWatchEventKinds.*;
import
java.nio.file.FileSystems;
public class FolderWatcher {
public static void main(String[] args) {
// define a folder
root
Path
myDir = Paths.get("D:/Chandra");
try {
for (;;) {
WatchKey
watckKey;
// WatchService
watcher = myDir.getFileSystem().newWatchService();
WatchService
watcher = FileSystems.getDefault().newWatchService();
myDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
try {
// wait for a key to
be available
watckKey = watcher.take();
}
catch
(InterruptedException ex) {
return;
}
List<WatchEvent<?>>
events = watckKey.pollEvents();
for (WatchEvent event : events) {
WatchEvent.Kind<?>
kind = event.kind();
// get file name
@SuppressWarnings("unchecked")
WatchEvent<Path>
ev =
(WatchEvent<Path>) event;
Path
fileName = ev.context();
if (event.kind() == ENTRY_CREATE) {
System.out.println("Created:
" + fileName.toString());
}
if (event.kind() == ENTRY_DELETE) {
System.out.println("Delete:
" +
fileName.toString());
}
if (event.kind() == ENTRY_MODIFY) {
System.out.println("Modify:
" +
fileName.toString());
}
}
// IMPORTANT: The
key must be reset after processed
boolean valid = watckKey.reset();
if (!valid) {
break;
}
}
}
catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
}