读取属性文件

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());
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值