java读取properties配置文件

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * Properties类的使用,这样使用这个类的可以方便的取到配置文件里的东西
 * 我们在其他类中直接调用以下方式便能读取到配置
 * SystemConfig.getProperty("name");
 * @author leejuen
 *
 */
public class SystemConfig {
	private static Properties systemConfig;
	private static String configPath;
	private SystemConfig() {}
	static
	{
		systemConfig = new Properties();
		configPath = "./sys-config.properties";    //设置配置文件路径
		try {
			/**
			 * 在使用Class.getResourceAsStream 时, 资源路径有两种方式,
			 * 一种以 / 开头,则这样的路径是指定绝对路径, 如果不以 / 开头,
			 * 则路径是相对与这个class所在的包的.在使用ClassLoader.getResourceAsStream时,
			 * 路径直接使用相对于classpath的绝对路径。
			 */
			Class classConfig = Class.forName("com.szkingdom.leejuen.SystemConfig");
			InputStream is = classConfig.getResourceAsStream(configPath);
			//InputStream is = new FileInputStream("sys-config.properties");
			systemConfig.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	public static String getProperty(String key) {
		return systemConfig.getProperty(key);
	}
}

 




posted @ 2014-08-13 12:13  leejuen  阅读(141)  评论(0编辑  收藏  举报