Skip to content

Instantly share code, notes, and snippets.

@alexdorand
Created January 4, 2016 16:28
Show Gist options
  • Save alexdorand/7f98dc868aa536db825f to your computer and use it in GitHub Desktop.
Save alexdorand/7f98dc868aa536db825f to your computer and use it in GitHub Desktop.
package com.folion.core.service;
import java.io.IOException;
import java.nio.charset.CoderResult;
import java.nio.file.*;
public class FileReader {
public void watch() throws IOException {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("/Users/programmer/folion.com");
try {
WatchKey key = dir.register(watcher,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException x) {
System.err.println(x);
}
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();
// This key is registered only
// for ENTRY_CREATE events,
// but an OVERFLOW event can
// occur regardless if events
// are lost or discarded.
if (kind == CoderResult.OVERFLOW) {
continue;
}
// The filename is the
// context of the event.
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path child = dir.resolve(filename);
// Verify that the new
// file is a text file.
// try {
// // Resolve the filename against the directory.
// // If the filename is "test" and the directory is "foo",
// // the resolved name is "test/foo".
// 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);
//Details left to reader....
}
// 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;
}
}
}
public static void main(String arg[]) throws IOException {
FileReader fileReader = new FileReader();
fileReader.watch();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment