Watch with thread event handler - Java File Path IO

Java examples for File Path IO:File Watcher

Description

Watch with thread event handler

Demo Code

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
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;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

class Print implements Runnable {
  private Path doc;
  Print(Path doc) {//from www . j  a  va  2s .co m
    this.doc = doc;
  }
  @Override
  public void run() {
    try {
      Thread.sleep(200);
      System.out.println("Printing: " + doc);
    } catch (InterruptedException ex) {
      System.err.println(ex);
    }
  }
}
public class Main {
  public static void main(String[] args)  throws IOException, InterruptedException{
    final Path path = Paths.get("C:/test");
    Map<Thread, Path> threads = new HashMap<>();    
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
      path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_DELETE);
      while (true) {
        final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);
        if (key != null) {
          for (WatchEvent<?> watchEvent : key.pollEvents()) {
            final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
            final Path filename = watchEventPath.context();
            final Kind<?> kind = watchEvent.kind();
            if (kind == StandardWatchEventKinds.OVERFLOW) {
              continue;
            }
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
              System.out
                  .println("Sending the document to print -> " + filename);
              Runnable task = new Print(path.resolve(filename));
              Thread worker = new Thread(task);
              worker.setName(path.resolve(filename).toString());
              threads.put(worker, path.resolve(filename));
              worker.start();
            }

            if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
              System.out.println(filename + " was successfully printed!");
            }
          }
          boolean valid = key.reset();
          if (!valid) {
            threads.clear();
            break;
          }
        }

        if (!threads.isEmpty()) {
          for (Iterator<Map.Entry<Thread, Path>> it = threads.entrySet()
              .iterator(); it.hasNext();) {
            Map.Entry<Thread, Path> entry = it.next();
            if (entry.getKey().getState() == Thread.State.TERMINATED) {
              Files.deleteIfExists(entry.getValue());
              it.remove();
            }
          }
        }
      }
    }
  }
}

Related Tutorials