Пример #1
0
  /** Process all events for the key queued to the watcher. */
  void processEvents() {
    for (; ; ) {

      // wait for key to be signaled
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();

        if (kind == OVERFLOW) {
          continue;
        }

        // The filename is the context of the event.
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path filename = ev.context();

        // Verify that the new file is a text file.
        try {
          Path child = dir.resolve(filename);
          if (!Files.probeContentType(child).equals("text/plain")) {
            System.err.format("New file '%s' is not a plain text file.%n", filename);
            continue;
          }
        } catch (IOException x) {
          System.err.println(x);
          continue;
        }

        // Email the file to the specified email alias.
        System.out.format("Emailing file %s%n", filename);
      }

      // Reset the key -- this step is critical if you want to receive
      // further watch events. If the key is no longer valid, the directory
      // is inaccessible so exit the loop.
      boolean valid = key.reset();
      if (!valid) {
        break;
      }
    }
  }