Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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