Skip to content

Instantly share code, notes, and snippets.

@samuelstein
Created October 23, 2018 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelstein/b4f8d6bd7a52fc2d1946a9c5ba2a7a52 to your computer and use it in GitHub Desktop.
Save samuelstein/b4f8d6bd7a52fc2d1946a9c5ba2a7a52 to your computer and use it in GitHub Desktop.
import model.IFileWatchListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
public class FileWatcher extends Thread {
private static final Logger LOG = LogManager.getLogger(FileWatcher.class.getName());
private Path path;
private List<IFileWatchListener> listeners = new ArrayList<>();
private String fileToObserve;
public FileWatcher(String path, String fileToObserve) {
this.path = Paths.get(path);
this.fileToObserve = fileToObserve;
}
public void addListeners(IFileWatchListener watchListener) {
this.listeners.add(watchListener);
}
// print the events and the affected file
private void printEvent(WatchEvent<?> event) {
WatchEvent.Kind<?> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
Path pathModified = (Path) event.context();
if (pathModified.getFileName().toString().equalsIgnoreCase(fileToObserve)) {
LOG.info("Entry modified: {}", pathModified);
for (IFileWatchListener listener : listeners) {
listener.fileChanged(event);
}
}
}
}
@Override
public void run() {
try {
WatchService watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
// loop forever to watch directory
while (true) {
WatchKey watchKey;
// Obtaining watch keys every 10 seconds
// final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);
watchKey = watchService.take(); // this call is blocking until events are present
// poll for file system events on the WatchKey
watchKey.pollEvents().forEach(this::printEvent);
// if the watched directed gets deleted, get out of run method
if (!watchKey.reset()) {
LOG.info("No longer valid");
watchKey.cancel();
watchService.close();
break;
}
}
} catch (InterruptedException ex) {
LOG.error("interrupted. Goodbye");
return;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
return;
}
}
}
import java.nio.file.WatchEvent;
public interface IFileWatchListener {
void fileChanged(WatchEvent<?> event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment