Skip to content

Instantly share code, notes, and snippets.

@benelog
Created July 15, 2014 08:43
Show Gist options
  • Save benelog/39359ae75ebe2c269381 to your computer and use it in GitHub Desktop.
Save benelog/39359ae75ebe2c269381 to your computer and use it in GitHub Desktop.
File watcher
import static java.nio.file.StandardWatchEventKinds.*;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
public class WatcherExample {
public static void main(String args[]) throws IOException, InterruptedException {
URL classFolder = WatcherExample.class.getClassLoader().getResource(".");
String monitorPath = classFolder.getFile();
System.out.println(monitorPath + " is watched");
watchDir(monitorPath);
}
public static void watchDir(String dir) throws IOException, InterruptedException {
WatchService service = FileSystems.getDefault().newWatchService();
Path parent = Paths.get(dir);
registerSubDirs(service, parent);
while (true) {
WatchKey key = service.take();
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.kind() + ": " + event.context());
}
boolean valid = key.reset();
if (!valid) {
break; // Exit if directory is deleted
}
}
}
private static void registerSubDirs(final WatchService service, Path parent)
throws IOException {
Files.walkFileTree(parent, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) throws IOException {
path.register(service, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment