Skip to content

Instantly share code, notes, and snippets.

@danielflower
Created April 22, 2017 08:54
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save danielflower/f54c2fe42d32356301c68860a4ab21ed to your computer and use it in GitHub Desktop.
Save danielflower/f54c2fe42d32356301c68860a4ab21ed to your computer and use it in GitHub Desktop.
Watching a single file in java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.*;
public class FileWatcher {
private static final Logger log = LoggerFactory.getLogger(FileWatcher.class);
private Thread thread;
private WatchService watchService;
public interface Callback {
void run() throws Exception;
}
/**
* Starts watching a file and the given path and calls the callback when it is changed.
* A shutdown hook is registered to stop watching. To control this yourself, create an
* instance and use the start/stop methods.
*/
public static void onFileChange(Path file, Callback callback) throws IOException {
FileWatcher fileWatcher = new FileWatcher();
fileWatcher.start(file, callback);
Runtime.getRuntime().addShutdownHook(new Thread(fileWatcher::stop));
}
public void start(Path file, Callback callback) throws IOException {
watchService = FileSystems.getDefault().newWatchService();
Path parent = file.getParent();
parent.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
log.info("Going to watch " + file);
thread = new Thread(() -> {
while (true) {
WatchKey wk = null;
try {
wk = watchService.take();
Thread.sleep(500); // give a chance for duplicate events to pile up
for (WatchEvent<?> event : wk.pollEvents()) {
Path changed = parent.resolve((Path) event.context());
if (Files.exists(changed) && Files.isSameFile(changed, file)) {
log.info("File change event: " + changed);
callback.run();
break;
}
}
} catch (InterruptedException e) {
log.info("Ending my watch");
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
log.error("Error while reloading cert", e);
} finally {
if (wk != null) {
wk.reset();
}
}
}
});
thread.start();
}
public void stop() {
thread.interrupt();
try {
watchService.close();
} catch (IOException e) {
log.info("Error closing watch service", e);
}
}
}
@danielflower
Copy link
Author

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org

@GZ315200
Copy link

GZ315200 commented Apr 6, 2021

thanx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment