curena
9/3/2015 - 8:41 PM

Watch a directory using Java WatchService

Watch a directory using Java WatchService

Path myDir = Paths.get(DIRECTORY_NAME);

WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
		StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

WatchKey watchKey = watcher.take();

while (watchKey != null) {
	for (WatchEvent event : watchKey.pollEvents()) {
		if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
			log.info(((Path) event.context()).getFileName().toString());
		}
	}
	watchKey.reset();
	watchKey = watcher.take();
}