用java写服务程序时经常会涉及到监控某些配置文件,当配置文件发生变化时实时重新加载该文件的内容到内存.实际上log4j里有现成的类FileWatchdog做了类似的工作.我们只需继承它,然后重写它的一些方法就可以了. /**使用log4j的监控狗 */ public class IPAccessFileWatchdog extends FileWatchdog { public IPAccessFileWatchdog(String filename){ super(filename); } public void doOnChange() { List<String> list = IPAccessController.this.loadIPRule(new File(this.filename)); if (list != null) { IPAccessController.this.ipRule = list.toArray(new String[list.size()]); } else { IPAccessController.this.ipRule = null; } LogLog.warn("ip access config load completed from file:" + filename); } } } FileWatchdog的代码也很简单,其实就是起一个线程,每隔固定的时间扫描一次监控的文件.我把代码也贴出来: ' // Contributors: Mathias Bogaert package org.apache.log4j.helpers; import java.io.File; import org.apache.log4j.helpers.LogLog; public abstract class FileWatchdog extends Thread { static final public long DEFAULT_DELAY = 60000; protected String filename; protected long delay = DEFAULT_DELAY; File file; long lastModif = 0; boolean warnedAlready = false; boolean interrupted = false; protected FileWatchdog(String filename) { this.filename = filename; file = new File(filename); setDaemon(true); checkAndConfigure(); } public void setDelay(long delay) { this.delay = delay; } abstract protected void doOnChange(); protected void checkAndConfigure() { boolean fileExists; try { fileExists = file.exists(); } catch(SecurityException e) { LogLog.warn("Was not allowed to read check file existance, file:["+ filename+"]."); interrupted = true; // there is no point in continuing return; } if(fileExists) { long l = file.lastModified(); // this can also throw a SecurityException if(l > lastModif) { // however, if we reached this point thislastModif = l; // is very unlikely.doOnChange();warnedAlready = false; } } else { if(!warnedAlready) {LogLog.debug("["+filename+"] does not exist.");warnedAlready = true; } } } public void run() { while(!interrupted) { try { Thread.sleep(delay); } catch(InterruptedException e) {// no interruption expected } checkAndConfigure(); } }}