String&XML

package com.huawei.ngbss.esb;
import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class FileListener extends TimerTask
{
private File file=null;
private long lastModified=0;
private Properties prop=new Properties();
private boolean fileFlag=true;
public boolean isFileFlag()
{
return fileFlag;
}

public void setFileFlag(boolean fileFlag)
{
this.fileFlag = fileFlag;
}

public Logger getLogger()
{
return logger;
}

public void setLogger(Logger logger)
{
this.logger = logger;
}

private Logger logger=Logger.getLogger(FileListener.class);

FileListener(String filePath)
{
if(filePath!=null)
{
this.file=new File(filePath);
if(!file.isFile())
{
logger.error("This file["+filePath+"]does not exist,please check it.");
return;
}

if(this.file.getName().endsWith(".properties"))
{
this.fileFlag=true;
}
else if(this.file.getName().endsWith(".xml"))
{
this.fileFlag=false;
}
else
{
logger.info("no thing to do......");
}
}
}

private boolean isFileUpdated()
{
if(this.fileFlag)
{
long lastUpdatedTime=file.lastModified();
//if this file has upate the lastUpdateTime will > 0
return lastUpdatedTime >this.lastModified;
}
else
{
return false;
}
}

public void loadFile()
{
if(this.fileFlag)
{
loadProperties();
}
else
{

}
}
public void loadProperties()
{
//set the lastModfied
this.lastModified=file.lastModified();
FileInputStream in=null;
try
{
logger.info("The Properties file["+getPath()+"] loading......");
in=new FileInputStream(file);
prop.load(in);
//print all properties
//get properties all property KeyNames
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.");

if("log4j.properties".equalsIgnoreCase(getFileName()))
{
PropertyConfigurator.configure(getProperties());
}
}
catch (Exception e)
{
logger.error("The file[" + getPath()
+ "] doesn't exist, reload file unsuccess.");
e.printStackTrace();
}
}
public void run()
{
if(isFileUpdated() && fileFlag)
{
logger.info("the Properties file["+getPath()+"] was modified.");
loadFile();
}
else if(isFileUpdated() && !fileFlag)
{
loadFile();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值