在项目中,经常会把.properties文件作为配置文件来读取,当运行时改变这种配置文件时,tomcat等容器并不会重新载入新值,这样就不得不另外想办法来实现。以下是实现的一种方法,仅供参考
// 不断监控文件
while (m_bIsMonitor) {
try{
// 判断文件是否已修改了,若已修改过
if (nModifiedTime != f.lastModified()) {
nModifiedTime = f.lastModified();
m_bIsModified = true;
//遍历HashMap的key并根据key从配置文件中更新HashMap
it = m_hm.keySet().iterator();
file = new FileInputStream(m_szFP);
properties = new Properties();
properties.load(file);
while(it.hasNext()){
szKey=(String)it.next();
szVal=properties.getProperty(szKey);
if (szVal != null) {
szVal = szVal.trim();
}
m_hm.put(szKey, szVal);
}
file.close();
}
}catch(IOException ioe){
System.out.println(this.getClass()+":syscfgfile path error!");
ioe.printStackTrace();
}
// 停顿间隔
try {
sleep(m_nInterval);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(this.getClass()+":Thread sleep error!");
}
}
class A{
private File file;
private Properties property=new Properties();
public A(){
init();
Thread t=new Thread(new Listener());
t.setDaemon(true);
t.start();
}
private void init(){
property.load(new FileInputStream(file));//重新加载文件
}
class Listener implements Runnable{//扫描文件改动
private long modifyTime=file.lastModified();
public void run(){
while(true){
long l=file.lastModified();
if(l>modifyTime){
modifyTime=l;
init();
}
Thread.sleep(100);
}
}
}
注意:重新加载文件时要同步,上面的因为Properties本身是线程安全的所以不用同步