Learning The "J"

Home » JAVA Learning » JAVA Core » Directory Watch

Category Archives: Directory Watch

Watching a Directory for Changes

JDK7’s java.nio.file package has a WatchService to support file change notification. You can use it to monitor a directory for changes.

You can also try jpathwatch (http://jpathwatch.wordpress.com/), which is an implementation of the WatchService interface and uses native OS functions, instead of polling.

The code below shows how you would use the Watch Service API. First, you have to create a WatchService for the file system and then register the directory you want to monitor with it. You have to specify which events (create, modify or delete) you are interested in receiving. Then start an infinite loop to wait for events. When an event occurs, a WatchKey is placed into the watch service’s queue and you have to call take to retrieve it. You can then query the key for events and print them out.

/*
  Watch the specified directory
  @param dirname the directory to watch
  @throws IOException
  @throws InterruptedException
 */
public static void watchDir(String dir)
    throws IOException, InterruptedException{
 
  //create the watchService
  final WatchService watchService = FileSystems.getDefault().newWatchService();
 
  //register the directory with the watchService
  //for create, modify and delete events
  final Path path = Paths.get(dir);
  path.register(watchService,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);
 
  //start an infinite loop
  while(true){
 
    //remove the next watch key
    final WatchKey key = watchService.take();
 
    //get list of events for the watch key
    for (WatchEvent watchEvent : key.pollEvents()) {
 
      //get the filename for the event
      final WatchEvent ev = (WatchEvent)watchEvent;
      final Path filename = ev.context();
 
      //get the kind of event (create, modify, delete)
      final Kind kind = watchEvent.kind();
 
      //print it out
      System.out.println(kind + ": " + filename);
    }
 
    //reset the key
    boolean valid = key.reset();
 
    //exit loop if the key is not valid
    //e.g. if the directory was deleted
      if (!valid) {
          break;
      }
  }
}

Here is a full working code

(more…)