4 import java.io.IOException;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
10 public class TestFileChangeNotification {
12 * Check every now and then that a certain file has not changed. If it has, then
13 * call the {@link #doOnChange} method.
18 public static abstract class FileWatchdog extends Thread {
20 private static final Logger LOGGER = LoggerFactory.getLogger(FileWatchdog.class);
22 * The default delay between every file modification check, set to 60
25 public static final long DEFAULT_DELAY = 60000;
27 * The name of the file to observe for changes.
29 private String filename;
32 * The delay to observe between every check. By default set
33 * {@link #DEFAULT_DELAY}.
35 private long delay = DEFAULT_DELAY;
38 private long lastModified = 0;
39 private boolean warnedAlready = false;
40 private boolean interrupted = false;
42 protected FileWatchdog(String filename) {
43 this.filename = filename;
44 file = new File(filename);
50 * Set the delay to observe between each check of the file changes.
53 * the frequency of file watch.
55 public void setDelay(long delay) {
60 * abstract method to be run when the file is changed.
62 protected abstract void doOnChange();
64 protected void checkAndConfigure() {
67 fileExists = file.exists();
68 } catch (SecurityException e) {
69 LOGGER.warn("Was not allowed to read check file existence, file:[" + filename + "].");
70 interrupted = true; // there is no point in continuing
75 long l = file.lastModified(); // this can also throw a
76 if (lastModified ==0) {
77 lastModified = l; // is very unlikely.
79 if (l > lastModified) { // however, if we reached this point this
80 lastModified = l; // is very unlikely.
82 warnedAlready = false;
86 LOGGER.debug("[" + filename + "] does not exist.");
94 while (!interrupted && !isInterrupted()) {
97 } catch (InterruptedException e) {
104 public static class SomeWatchFile extends FileWatchdog{
106 protected SomeWatchFile(String filename) {
112 protected void doOnChange() {
113 System.out.println("File has changed");
117 public static void main(String args[]) throws IOException {
118 SomeWatchFile someWatchFile = new SomeWatchFile ("watchedFile.txt");
119 someWatchFile.start();
121 String fileName = "watchedFile.txt";
122 File tempFile = new File(fileName);
123 tempFile.createNewFile();
125 System.out.println("1. Press F5 in eclipse to see and modify 2. Press enter to exit");
127 System.out.println("Remove file "+fileName);