一、前言
基于事件原理(事件对象、事件监听器、事件源)、java.util.TimerTask定时器任务定义文件监控器FileMonitor类,其中包括onModifyFile文件修改监听器Listener接口定义、文件内部监听容器InnerListeners实现类、文件事件源路径监听等,详情参见代码示例。
二、代码示例
import java.io.File;@b@import java.util.TimerTask;@b@import java.util.concurrent.ConcurrentHashMap;@b@import java.util.concurrent.CopyOnWriteArrayList;@b@@b@public class FileMonitor extends TimerTask {@b@ @b@ /**@b@ * 监听器@b@ */@b@ public interface Listener {@b@ public void onModifyFile(File file);@b@ }@b@ @b@ /**@b@ * 内部监听容器@b@ */@b@ private static class InnerListeners {@b@ public final String filePath;@b@ public final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();@b@ public long mdate; @b@ @b@ public InnerListeners(String filePath) {@b@ this.filePath = filePath;@b@ File file = new File(filePath); @b@ mdate = file.exists() ? file.lastModified() : -1; @b@ }@b@ @b@ public void add(Listener listener) {@b@ if (listener != null) {@b@ listeners.add(listener);@b@ }@b@ }@b@ @b@ public void remove(Listener listener) {@b@ if (listener != null) {@b@ listeners.remove(listener);@b@ } @b@ }@b@ @b@ public boolean isEmpty() {@b@ return listeners.isEmpty();@b@ }@b@ @b@ public void checkModify() {@b@ File file = new File(filePath); @b@ long new_mdate = file.exists() ? file.lastModified() : -1;@b@ if (new_mdate != mdate) {@b@ for (Listener listener : listeners) {@b@ listener.onModifyFile(file);@b@ }@b@ mdate = new_mdate;@b@ }@b@ }@b@ }@b@ @b@ /**@b@ * 文件监听器@b@ */@b@ @b@ private final ConcurrentHashMap<String, InnerListeners> listenersMap = new ConcurrentHashMap<String, InnerListeners>();@b@ @b@ public void listen(String filePath, Listener listener) {@b@ InnerListeners listeners = listenersMap.get(filePath);@b@ if (listeners == null) {@b@ listeners = new InnerListeners(filePath);@b@ listenersMap.put(filePath, listeners);@b@ }@b@ listeners.add(listener);@b@ }@b@ @b@ public void unListen(String filePath, Listener listener) {@b@ InnerListeners listeners = listenersMap.get(filePath);@b@ if (listeners != null) {@b@ listeners.remove(listener);@b@ if (listeners.isEmpty()) {@b@ listenersMap.remove(filePath);@b@ }@b@ }@b@ }@b@@b@ @Override@b@ public void run() {@b@ for (InnerListeners listeners : listenersMap.values()) {@b@ listeners.checkModify();@b@ }@b@ }@b@@b@}