Sunday, 21 October 2012

File Watcher

Java 7 has a new WatchService class which can be used to monitor
changes to a directory, as an alternative to polling a directory for changes. Below is an example:

package com.rizvn;
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 java.nio.file.StandardWatchEventKinds;

/**
 * @author riz
 */
public class FileWatcher {

    public static void main(String[] args) {

        //Path to watch
        Path path = Paths.get("C:/TEMP");

        System.out.println("Running Watcher...");

        try {
          //loop forever
         while(true){
          //create watcher service
          WatchService watcher = path.getFileSystem().newWatchService();

            //Tell watcher which file events to  listen to
            path.register(watcher,
                          StandardWatchEventKinds.ENTRY_CREATE, //listen for creations
                          StandardWatchEventKinds.ENTRY_DELETE, //listen for deletions
                          StandardWatchEventKinds.ENTRY_MODIFY); //listen for modification

            //blocking call to wait for event
            WatchKey watckKey = watcher.take();

            List <WatchEvent<?>> events = watckKey.pollEvents();

           //iterate over events and handle
           for (WatchEvent<?> event : events) {
            //handle creation
             if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
               System.out.println("Created: " + event.context().toString());
             }

             //handle deletion
             if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
               System.out.println("Delete: " + event.context().toString());
             }

             //handle modification
             if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
               System.out.println("Modify: " + event.context().toString());
               }
             }
         }

        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }

        System.out.println("Ending watcher");
    }
}

No comments:

Post a Comment