Skip to content

Instantly share code, notes, and snippets.

@krobelus
Created April 30, 2016 20:19
Show Gist options
  • Select an option

  • Save krobelus/44234893c8ffef4bfd6f5d08bdb542e5 to your computer and use it in GitHub Desktop.

Select an option

Save krobelus/44234893c8ffef4bfd6f5d08bdb542e5 to your computer and use it in GitHub Desktop.
package prsw3;
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 static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
class FileWatcher implements Runnable {
private Main main;
private String root;
public FileWatcher(Main main) {
this.main = main;
this.root = this.main.sourcepath;
}
@Override
public void run() {
Path rootp = Paths.get(root);
WatchService watcher;
try {
watcher = FileSystems.getDefault().newWatchService();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
return;
}
try (Stream<Path> paths = Files.walk(rootp)) {
paths.forEach(p -> {
if (watchp(p)) {
main.enqueueFileChange(new FileChange(p));
}
if (Files.isDirectory(p)) {
System.out.println("adding watch for directory: " + p);
try {
p.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
while (main.isRunning()) {
try {
WatchKey k = watcher.take();
k.pollEvents().stream().map((evt) -> (WatchEvent<Path>) evt).forEach((pevt) -> {
Path relPath = pevt.context();
Path dir = (Path) k.watchable();
Path absPath = dir.resolve(relPath);
if (watchp(absPath) || pevt.kind() == ENTRY_DELETE) {
main.enqueueFileChange(new FileChange(pevt, dir));
System.out.printf("CHANGE %s, dir %s, file %s\n", pevt.kind().toString(), dir.toString(), relPath.toString());
if (Files.isDirectory(absPath)) {
if (pevt.kind() == ENTRY_CREATE) {
try {
System.out.println("adding watch for directory: " + absPath);
absPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (Exception e) {
}
}
}
}
});
k.reset();
} catch (InterruptedException e) {
}
}
}
private static boolean watchp(Path p) {
String s = p.toString();
return Files.isDirectory(p) || s.endsWith(".txt") || s.endsWith(".xml") || s.endsWith(".java");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment