properties类文件的监听 PropertyFileListener

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
* @author Xgw123485 property 文件监听器 2011-12-28
*/
public class PropertyFileListener extends FileListener
{
private Logger logger = Logger.getLogger(PropertyFileListener.class);

/**
* 构造函数,初始化文件实例
* @param filePath 文件路径
*/
PropertyFileListener(String filePath)
{
if (filePath != null)
{
//根据路探测器得到文件.
this.file = new File(filePath);
if (!file.isFile())
{
logger.error("The file[" + filePath
+ "] does not exist,please check it");
return;
}
else
{
logger.info("nothing to do...");
}
}
}
/**
* 确认文件是否更新
* @return 文件有更新,返回true,否则返回false
*/
public boolean isFileUpdate()
{
//得到文件最后修改的时候,如果有改动,则返回1,否则返回0
long lastUpdateTime = file.lastModified();
return lastUpdateTime > this.lastModified;
}

/**
* 加载文件,将文件的内容以键值对保存
*/
public void loadFile()
{
loadProperties();
}

/**
* 根据键返回属性值
* @return 传入键所对应的值
*/
public String getPropertyValue(String key)
{
return this.getProperties().getProperty(key);
}

/**
* 加载配置文件 2011-12-28,Xgw123485
*/
private void loadProperties()
{
// 更新时间
this.lastModified = file.lastModified();
FileInputStream in = null;
try
{
logger.info("The properties file[" + getPath() + "] loading...");
in = new FileInputStream(file);
prop.load(in);
Enumeration<?> enu = prop.propertyNames();
StringBuffer buf = new StringBuffer();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
buf.append(" key:").append(key).append(", value:")
.append(prop.getProperty(key)).append("\n");
}
logger.info(buf.toString());
logger.info("The properties file["+getPath()+"] load complete.");
//如果是log4j.properties文件更新,需要加载配置 以便立即生效
if("log4j.properties".equalsIgnoreCase(getFileName()))
{
PropertyConfigurator.configure(getProperties());
}
}
catch (Exception e)
{
logger.error("The file["+getPath()+"] does not exist,reload file unsuccess.");
}
finally
{
try
{
if(null != in)
{
in.close();
}
}
catch (Exception e2)
{
logger.error(e2.getMessage(),e2);
}
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值