Watching Directory in Java with NIO 2.0 ...Wonderful !!! I love java for that


The java.nio.file package provides a file change notification API, called the Watch Service API. This API allows you to register a directory (or directories) with the watch service — when registering you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When one comes in, it is handled as needed.

for (;;) {

//wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {

for (WatchEvent event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();

//This key is registered only for ENTRY_CREATE events,
//but an OVERFLOW event can occur regardless if events are
//lost or discarded.
if (kind == OVERFLOW) {

//The filename is the context of the event.
WatchEvent ev = (WatchEvent)event;
Path filename = ev.context();

//Verify that the new file is a text file.
try {
//Resolve the filename against the directory.
//If the filename is "test" and the directory is "foo",
//the resolved name is "test/foo".
Path child = dir.resolve(filename);
if (!Files.probeContentType(child).equals("text/plain")) {
System.err.format("New file '%s' is not a plain text file.%n", filename);
} catch (IOException x) {

//Email the file to the specified email alias.
System.out.format("Emailing file %s%n", filename);
//Details left to reader....

//Reset the key -- this step is critical if you want to receive
//further watch events. If the key is no longer valid, the directory
//is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {

When registering an object with the watch service, you specify the types of events you want to monitor. The supported StandardWatchEventKind event types are:

* ENTRY_CREATE — a directory entry is created.
* ENTRY_DELETE — a directory entry is deleted.
* ENTRY_MODIFY — a directory entry is modified;
* OVERFLOW — indicates that events may have been lost or discarded. You do not have to register for this event to receive it.

The following code snippet shows how to register a Path instance for all three event types:

import static java.nio.file.StandardWatchEventKind.*;

Path dir = ...;
try {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException x) {


:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Post a Comment