1 43 package net.jforum.util; 44 45 import java.io.File ; 46 import java.util.HashMap ; 47 import java.util.Map ; 48 import java.util.Timer ; 49 import java.util.TimerTask ; 50 51 import org.apache.log4j.Logger; 52 53 59 public class FileMonitor 60 { 61 private static Logger logger = Logger.getLogger(FileMonitor.class); 62 private static final FileMonitor instance = new FileMonitor(); 63 private Timer timer; 64 private Map timerEntries; 65 66 private FileMonitor() { 67 this.timerEntries = new HashMap (); 68 this.timer = new Timer (true); 69 } 70 71 public static FileMonitor getInstance() { 72 return instance; 73 } 74 75 82 public void addFileChangeListener(FileChangeListener listener, 83 String filename, long period) { 84 this.removeFileChangeListener(filename); 85 86 logger.info("Watching " + filename); 87 88 FileMonitorTask task = new FileMonitorTask(listener, filename); 89 90 this.timerEntries.put(filename, task); 91 this.timer.schedule(task, period, period); 92 } 93 94 100 public void removeFileChangeListener(String filename) { 101 FileMonitorTask task = (FileMonitorTask)this.timerEntries.remove(filename); 102 103 if (task != null) { 104 task.cancel(); 105 } 106 } 107 108 private class FileMonitorTask extends TimerTask { 109 private FileChangeListener listener; 110 private String filename; 111 private File monitoredFile; 112 private long lastModified; 113 114 public FileMonitorTask(FileChangeListener listener, String filename) { 115 this.listener = listener; 116 this.filename = filename; 117 118 this.monitoredFile = new File (filename); 119 if (!this.monitoredFile.exists()) { 120 return; 121 } 122 123 this.lastModified = this.monitoredFile.lastModified(); 124 } 125 126 public void run() { 127 long latestChange = this.monitoredFile.lastModified(); 128 if (this.lastModified != latestChange) { 129 this.lastModified = latestChange; 130 131 this.listener.fileChanged(this.filename); 132 } 133 } 134 } 135 } 136 | Popular Tags |