1. 程式人生 > >讀取properties檔案,工具類。

讀取properties檔案,工具類。

我們通常都會遇到需要解析properties檔案內容的需求,下面就貼上讀取properties檔案屬性的工具類  與  呼叫方法

解析properties工具類

import java.io.InputStream;
import java.util.Properties;
/**
 * 獲取指定屬性名的屬性值
 * @author ZL
 * @version 1.0
 */
public class GetPropertiesValue {
	private static GetPropertiesValue getPropValueIstance; //本類自己例項
	private static Properties properties = new Properties();
	private static InputStream is;
	
	/**
	 * 獲取本類物件(單例模式)
	 * @return 本類物件
	 */
	public static GetPropertiesValue getInstance(){
		if(getPropValueIstance == null){
			getPropValueIstance = new GetPropertiesValue();
		}
		return getPropValueIstance;
	}
	
	/**
	 * 返回properties檔案中屬性的值
	 * @param path properties檔案路徑
	 * @param PropertyName properties檔案中的屬性名
	 * @return properties檔案中屬性的值
	 */
	public static String getValue(String path, String PropertyName){
		try {
			is = GetPropertiesValue.class.getClassLoader().getResourceAsStream(path);
			properties.load(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("異常:路徑或檔名有誤!路徑前請不要加\"/\"");
		}
		String propertyValue = (String) properties.get(PropertyName);
		return propertyValue;
	}

}
呼叫方法
private static final String configUrl="Config.properties";
	
	public static final String KEY = GetPropertiesValue.getValue(configUrl, "key");