为了代码的可移植,我们在记取配置文件时,也要做一个小小的处理,我把我的习惯做法和大家分享一下:
首我把配置文件都放到src下的conf文件夹下:
[img]/members/xiaoyuer/code.jpg[/img]
下面把代码也粘出来给大家看看:
package com.ce.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 获取配置文件
*
* @author xiaoyuer
*
*/
public final class ConfigUtil {
private final boolean DEBUG=false;//实现条件编译
private final Logger logger=Logger.getLogger(ConfigUtil.class);
private final Properties prop = new Properties();
private String configfile;
/**
*
* @param configfilename classpath中conf文件夹下的文件名
*/
public ConfigUtil(String configfilename) {
this.configfile = configfilename;
LoadConfigFile();
if(DEBUG)
{
System.out.println("正在读取配置文件:"+this.configfile);
}
}
/**
* 获取Properties
* @return Properties
*/
public Properties getProperties()
{
return this.prop;
}
/**
* 加载配置文件
*/
private void LoadConfigFile() {
InputStream is=this.getClass().getClassLoader().getResourceAsStream("conf/" + this.configfile);
if (null!=is) {
try {
prop.load(is);
} catch (IOException e) {
e.printStackTrace(System.err);
logger.error("加载配置文件出错:" + e.getMessage());
} catch (Exception ex) {
ex.printStackTrace(System.err);
logger.error("加载配置文件出错:" + ex.getMessage());
}
} else {
logger.error("无法找到配置文件:" + this.configfile);
}
}
/**
* 获取属性值
*
* @param key 键
* @return String 值
*/
public String getProperty(String key) {
String value;
if (prop.containsKey(key)) {
value = (String) prop.get(key);
} else {
value = "";
logger.warn("在配置文件" + this.configfile + "中无法找到属性:" + key);
}
return value;
}
}
注意:不要使用ClassLoader.getSystemResourceAsStream("");来获取资源,因为这样经常会找不到.
同时我们可以把资源放到JAR里,方便使用,可以放到classpath中。
是否要把配置文件放到conf文件夹是,个人的习惯问题,你也可以放到src目录下。
最关键是要用一个实例来获取资源(在我的例子中用this)。
[code]
|
|