配置檔案讀取類
阿新 • • 發佈:2019-01-04
package com.wp.tool; import java.util.Date; import java.util.HashMap; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 資原始檔讀取工具 * @author pengwu7 * @date 2017年9月7日 */ public class PropertiesFileUtil { // 當開啟多個資原始檔時,快取資原始檔 private static HashMap<String, PropertiesFileUtil> configMap = new HashMap<String, PropertiesFileUtil>(); // 開啟檔案時間,判斷超時使用 private Date loadTime = null; // 資原始檔 private ResourceBundle resourceBundle = null; // 預設資原始檔名稱 private static final String NAME = "config"; // 快取時間 private static final Integer TIME_OUT = 60 * 1000; // 私有構造方法,建立單例 private PropertiesFileUtil(String name) { this.loadTime = new Date(); this.resourceBundle = ResourceBundle.getBundle(name); } public static synchronized PropertiesFileUtil getInstance() { return getInstance(NAME); } public static synchronized PropertiesFileUtil getInstance(String name) { PropertiesFileUtil conf = configMap.get(name); if (null == conf) { conf = new PropertiesFileUtil(name); configMap.put(name, conf); } // 判斷是否開啟的資原始檔是否超時1分鐘 if ((new Date().getTime() - conf.getLoadTime().getTime()) > TIME_OUT) { conf = new PropertiesFileUtil(name); configMap.put(name, conf); } return conf; } // 根據key讀取value public String get(String key) { try { String value = resourceBundle.getString(key); return value; }catch (MissingResourceException e) { return ""; } } // 根據key讀取value(整形) public Integer getInt(String key) { try { String value = resourceBundle.getString(key); return Integer.parseInt(value); }catch (MissingResourceException e) { return null; } } // 根據key讀取value(布林) public boolean getBool(String key) { try { String value = resourceBundle.getString(key); if ("true".equals(value)) { return true; } return false; }catch (MissingResourceException e) { return false; } } public Date getLoadTime() { return loadTime; } }
PropertiesFileUtil.getInstance("config").get("xxx");
PropertiesFileUtil.getInstance().get("xxx");