获取配置文件属性值

获取配置文件属性值

一.目的: 获取xxx.properties中配置的属性值.

(1)  sysconfig.properties配置如下:
a=aaaaaaaa
b=bbbbbbbb
c=cccccccc
d=dddddddd


(2)  工具类代码如下:


import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class SysConfigPropertiesHandler {
	
	private static Properties defaultProperties;
	
	public SysConfigPropertiesHandler(String propertiesName){
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null) {
			classLoader = SysConfigPropertiesHandler.class.getClassLoader();
		}
		try {
			InputStream is = classLoader.getResourceAsStream(propertiesName);
			defaultProperties = new Properties();
			defaultProperties.load(is);
		} catch (Exception e) {
			try {
				throw new Exception("装载属性资源参数文件出错.", e);
			} catch (Exception e1) {
			}
		}
	}
	
	/**
	 * 返回缺省属性文件[xxx.properties]属性值
	 * 
	 * @param pKey
	 * @return String
	 */
	public String getProperty(String pKey) {
		String value = defaultProperties.getProperty(pKey, "");
		return value;
	}
	
	
	/**
	 * 返回多个[xxx.properties]属性值
	 * @param map
	 * @return
	 */
	public Map<String, String> getPropertys(Map<String, String> map) {
		for (String key : map.keySet()) {
			map.put(key, defaultProperties.getProperty(key, ""));
		}
		return map;
	}
	
	
	
}




(3)  测试代码如下:

import java.util.HashMap;
import java.util.Map;
import cn.nuohy.util.config.SysConfigPropertiesHandler;

public class MyUtil{
	public static void main(String[] args) {
		SysConfigPropertiesHandler handler = new SysConfigPropertiesHandler("sysconfig.properties");
		Map<String, String> map = new HashMap<String, String>();
		map.put("a", "");
		map.put("b", "");
		map.put("c", "");
		map.put("d", "");
		
		Map<String, String> propertys = handler.getPropertys(map);
		for (String m : propertys.keySet()) {
			
			System.out.println(m+"   "+propertys.get(m));
		}
	}
}


(4)  测试结果:







你可能感兴趣的:(java)