Share this page 

Detect File Modification Event (Java 7)Tag(s): IO


Java 7 provides a mechanism to get notification on file change without polling (WatchService).

In this example, we set up a thread to watch CREATE event in a given folder. DELETE and MODIFY can also be watched.

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public class WatchThread extends Thread {
  Path myDir;
  WatchService watcher;

  WatchThread(String path) {
    try {
      myDir = Paths.get(path);
      watcher =
        myDir.
           getFileSystem().
              newWatchService();
      myDir.register
       (watcher, StandardWatchEventKinds.ENTRY_CREATE);
    }

    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void run() {
    while (true) {
      try {
        WatchKey watchKey = watcher.take();
        List<WatchEvent<?>> events = watchKey.pollEvents();
        for (WatchEvent<?> event : events) {
          // You can listen for these events too :
          //     StandardWatchEventKinds.ENTRY_DELETE
          //     StandardWatchEventKinds.ENTRY_MODIFY
          if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
            System.out.println("Created: " + event.context().toString());
          }
        }
        watchKey.reset();
      }
      catch (Exception e) {
        System.out.println("Error: " + e.toString());
      }
    }
  }
}
To use it :
public class WatchDemo {
  public static void main (String args []) {
   new WatchThread("C:/temp").start();
   System.out.println("WatchThread is running!");
  }
}

See also : this related howto and this one too.


mail_outline
Send comment, question or suggestion to howto@rgagnon.com