java中讀取properties檔案內容
阿新 • • 發佈:2019-02-03
package com.tgb.SpringActivemq.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; public class MqPropertyUtil { private static final Logger logger = Logger.getLogger(MqPropertyUtil.class); private static Properties props; static { loadProps(); } synchronized static private void loadProps() { logger.info("開始載入properties檔案內容......."); props = new Properties(); InputStream in = null; try { // 第一種,通過類載入器進行獲取properties檔案流 in = MqPropertyUtil.class.getClassLoader().getResourceAsStream("mq.properties"); // 第二種,通過類進行獲取properties檔案流 // in = PropertyUtil.class.getResourceAsStream("/mq.properties"); props.load(in); } catch (FileNotFoundException e) { logger.error("jdbc.properties檔案未找到"); } catch (IOException e) { logger.error("出現IOException"); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { logger.error("jdbc.properties檔案流關閉出現異常"); } } logger.info("載入properties檔案內容完成..........."); logger.info("properties檔案內容:" + props); } public static String getProperty(String key) { if (null == props) { loadProps(); } return props.getProperty(key); } public static String getProperty(String key, String defaultValue) { if (null == props) { loadProps(); } return props.getProperty(key, defaultValue); } }