1. 程式人生 > >配置文件.properties的使用

配置文件.properties的使用

獲取 building util == per ack under exce consola

.properties是以鍵值對的形式保存數據,比文件保存更方便讀取,而且不用修改源代碼,不用重新編譯源文件。多用於保存配置數據,如jndi,cookie屬性,上傳下載目錄等等。另外,保存特殊化的內容十分有用,比如河北代碼需要前臺顯示“河北”字樣,雲南代碼需要顯示“雲南”字樣,用properties就不用修改源碼了。只需要河北寫一個配置文件,雲南寫一個配置文件。1、寫好配置文件,在buildingpath中設置為源。2、寫讀取配置文件的靜態函數。(如ConfigConstants.java)package com.wondersgroup.core.constant;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.Properties;
import org.apache.commons.lang.StringUtils;
public class ConfigConstants { /** 單體實例 */ private static ConfigConstants instance;
/** 配置屬性 */ private Map<String, String> config = new HashMap<String, String>();
/** * 私有構造器 */ private ConfigConstants() { }
/** * @return 返回 instance。 */ public static ConfigConstants getInstance() { if (instance == null) { instance = new ConfigConstants(); } return instance; }
/** * 獲取配置屬性 * * @param key * @return */ public String get(String key) { return config.get(key); }
/** * 初始化配置屬性 * * @throws IOException */ public void init() throws IOException { // 讀取默認配置文件 this.read("/config.properties");
// 擴展配置文件路徑配置項名稱 String ext = "config.ext";
// 支持多重繼承,循環讀取配置 while (StringUtils.isNotBlank(this.config.get(ext))) { // 讀取擴展配置文件路徑 String path = this.config.get(ext);
// 清除配置屬性中已讀取的擴展配置文件路徑 this.config.remove(ext);
// 讀取擴展配置文件 this.read(path); } }
/** * 讀取配置文件內容並將配置加載至內存 * * @param conf 配置文件路徑 * @throws IOException */ private void read(String conf) throws IOException { if (StringUtils.isNotBlank(conf)) { InputStream is = null; Properties props = new Properties();
try { is = ConfigConstants.class.getResourceAsStream(conf); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); props.load(br); Enumeration<?> propKeys = props.propertyNames(); while (propKeys.hasMoreElements()) { String propName = (String) propKeys.nextElement(); String propValue = props.getProperty(propName);
this.config.put(propName, propValue); } } finally { if (is != null) { is.close(); } } } }}3、這時配置文件中的內容已經以map形式放在內存池中,之後程序中可以用ConfigConstants
.getInstance().get("key")來取得相應value值。附註:擴展配置文件的使用,在properties中有此鍵值“config.ext”(在ConfigConstants.java中)即可,比如:config.ext /config-yn.properties


來自為知筆記(Wiz)

配置文件.properties的使用