Watch directory for modification : WatchService « JDK 7 « Java






Watch directory for modification


import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Test {
  public static void main(String[] args) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    Path dir = FileSystems.getDefault().getPath("/usr/a");

    WatchKey key = dir.register(watcher, ENTRY_MODIFY);

    while (true) {
      key = watcher.take();
      for (WatchEvent<?> event : key.pollEvents()) {
        if (event.kind() == ENTRY_MODIFY) {
          System.out.println("Home dir changed!");
        }
      }
      key.reset();
    }
  }
}

 








Related examples in the same category

1.Monitoring file events using WatchEvents