|
| 1 | +package de.softwertiger.filewatch; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.nio.file.FileSystems; |
| 5 | +import java.nio.file.Path; |
| 6 | +import java.nio.file.WatchEvent; |
| 7 | +import java.nio.file.WatchKey; |
| 8 | +import java.nio.file.WatchService; |
| 9 | + |
| 10 | +import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; |
| 11 | +import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; |
| 12 | + |
| 13 | +public class OnFileChangeRunner { |
| 14 | + private final Path watchDir; |
| 15 | + private final Path watchFile; |
| 16 | + private final WatchService watchService; |
| 17 | + |
| 18 | + private OnFileChangeRunner(final Path watchFile) throws IOException { |
| 19 | + this.watchFile = watchFile; |
| 20 | + watchDir = watchFile.getParent(); |
| 21 | + watchService = FileSystems.getDefault().newWatchService(); |
| 22 | + watchDir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY); |
| 23 | + } |
| 24 | + |
| 25 | + public static OnFileChangeRunner registerForFile(final Path watchFile) throws IOException { |
| 26 | + return new OnFileChangeRunner(watchFile); |
| 27 | + } |
| 28 | + |
| 29 | + public void runOnFileChange(final Runnable runnable) { |
| 30 | + try { |
| 31 | + tryRunOnFileChange(runnable); |
| 32 | + } catch (IOException e) { |
| 33 | + throw new Error(e); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private void tryRunOnFileChange(final Runnable runnable) throws IOException { |
| 38 | + try { |
| 39 | + final WatchKey take = watchService.take(); |
| 40 | + while (!Thread.interrupted()) { |
| 41 | + for (final WatchEvent<?> watchEvent : take.pollEvents()) { |
| 42 | + final WatchEvent<Path> ev = cast(watchEvent); |
| 43 | + if (watchFile.equals(watchDir.resolve(ev.context()))) { |
| 44 | + runnable.run(); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } catch (InterruptedException e) { |
| 49 | + // Ignore |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @SuppressWarnings("unchecked") |
| 54 | + private static <T> WatchEvent<T> cast(WatchEvent<?> event) { |
| 55 | + return (WatchEvent<T>) event; |
| 56 | + } |
| 57 | +} |
0 commit comments