1、读取webroot下面的web-inf 下面属性文件
public class CMConfig {
private static Properties ini;
private CMConfig() {
}
/**
* 从配置文件中更新ini对象
*/
// TODO 考虑从 context-param 参数中获取绝对路径, 可更灵活
public static synchronized void update() {
String iniFile = System.getProperty("chenming.root")
+ "/META-INF/chenming.properties";
CMConfig.update(iniFile);
}
/**
* 从指定的文件中更新ini对象
*
* @param iniFile
* 配置文件的绝对地址
*/
public static synchronized void update(String iniFile) {
try {
Properties ini = new Properties();
ini.load(new InputStreamReader(new FileInputStream(iniFile),
"UTF-8"));
CMConfig.ini = ini;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
if (CMConfig.ini == null) {
CMConfig.update();
}
return CMConfig.ini.getProperty(key);
}
}
第二种方式读取类路径下属性文件
package com.bitbao.cm.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 功能描述:该类负责读取fileupload.properties文件内容
* 创建时间:2010-12-06
* @author 徐士刚
* @version 1.0.0
*/
public class CommonReaderProperty extends Properties{
private static final long serialVersionUID = 1L;
private final Logger logger = Logger.getLogger(this.getClass());
private static CommonReaderProperty readerProperty;
/**
* 创建当前类的实例
* @return
*/
public static CommonReaderProperty getReaderProperty(){
if(readerProperty==null){
makeInstance();
}
return readerProperty;
}
private static synchronized void makeInstance(){
if(readerProperty==null){
readerProperty = new CommonReaderProperty();
}
}
/**
* 加载资源文件
*/
private CommonReaderProperty(){
InputStream is = this.getClass().getResourceAsStream("/fileupload.properties");
try {
load(is);
} catch (IOException e) {
logger.info("加载jdbc.properties文件时异常!异常发生在com.future.util.CommonReaderProperty类的私有构造方法,异常信息:"+e.getMessage(),e.fillInStackTrace());
}
}
}