Watch for create, delete, and modify events for a path and report the type of event and the file where it occurred - Java File Path IO

Java examples for File Path IO:File Watcher

Description

Watch for create, delete, and modify events for a path and report the type of event and the file where it occurred

Demo Code

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Main {
  public static void main(String[] args)  throws Exception{
    Path path = Paths.get("C:/folder1");
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
      path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_MODIFY,
          StandardWatchEventKinds.ENTRY_DELETE);
      while (true) {
        final WatchKey key = watchService.take();
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
          final Kind<?> kind = watchEvent.kind();
          if (kind == StandardWatchEventKinds.OVERFLOW) {
            continue;
          }//from   w ww . ja  va  2 s  .  com
          final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
          final Path filename = watchEventPath.context();
          System.out.println(kind + " -> " + filename);
        }
        // reset the key
        boolean valid = key.reset();
        if (!valid) {
          break;
        }
      }
    }
  }
}

Related Tutorials