properties資源文件是放在resource目錄下的:html
新建工具類:java
package com.demo.utils; import java.io.InputStream; import java.util.Properties; public class PropertyUtil { /** * 解析properties文件。 * * @param path:properties文件的路徑 * @param key: 獲取對應key的屬性 * @return String:返回對應key的屬性,失敗時候爲null。 */ public static String getPropertyByKey(String path, String key) throws Exception { String result = null; InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(path); Properties p = new Properties(); p.load(is); result = p.getProperty(key); return result; } public static void main(String[] args) { String url = ""; try { url = PropertyUtil.getPropertyByKey("api.properties", "dc_url"); } catch (Exception e) { e.printStackTrace(); //單文件運行測試時是獲取不到資源文件的,需在項目中 System.out.println("出錯啦"); } System.out.println(url); } }
實際項目中引用時,以下:api
String url = ""; try { url = PropertyUtil.getPropertyByKey("api.properties", "dc_url"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("從資源文件獲取url時出錯", e); }
放在其餘目錄下的資源文件能夠參考:http://www.javashuo.com/article/p-zborvtll-et.html工具