天天看點

擷取配置檔案屬性值

擷取配置檔案屬性值

一.目的: 擷取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)  測試結果:

擷取配置檔案屬性值