wikipedia

Support Wikipedia

Wednesday, December 21, 2011

Java 7 monitoring files/folders

Java 7 has this new watchservice which is a welcome development and you can read about it in many blogs as well as the oracle site. I tried playing with it using the code sample from some of the blogs. But unfortunately it seemed to work only the very first time and not after that.
Here is the code

public FileWatcher(String directoryPath) throws IOException {
        this.directoryPath  = directoryPath;
        FileSystem fileSystem = FileSystems.getDefault();
        watcher = fileSystem.newWatchService();
        
        Path myDir = fileSystem.getPath(this.directoryPath);
        myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, 
                  StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        monitorFolder();
} 
 
private void monitorFolder() {
  executor = Executors.newSingleThreadScheduledExecutor();
  executor.submit(this);
} 
 
public void run() {
  WatchKey watckKey = null;
  try {
   while(!shutdown ) {
    watckKey = watcher.take();
    events = watckKey.pollEvents();
    listener.processEvent(events);       
   }
  } catch (InterruptedException e) {
   logger.error("Error monitoring directory", e);
  }
} 

Some more beating around the bush and googling I discovered that the WatchKey needs to be reset for subsequent events to flow through to the listener.
Wonder why this strange behaviour. Anyhow here is the fix and after that everything was fine and dandy!

public void run() {
  WatchKey watchKey = null;
  try {
   while(!shutdown ) {
    watchKey = watcher.take();
    events = watchKey.pollEvents();
    listener.processEvent(events);
          
    watchKey.reset();   }
  } catch (InterruptedException e) {
   logger.error("Error monitoring directory", e);
  }
} 
 

Found out later by paying more attention(!!) to the article on the oracle site that resetting the watchkey is key
to getting future events.

No comments:

Post a Comment