在實際開發工作中,我們又是會將一些路徑文件配置放在properties文件中,這樣我們需要修改路徑的時候就只需要寫該一下配置文件就行了,不需要在代碼中挨個挨個的去改。但是我們怎樣獲得配置文件中的值呢?其實這個很簡單,我們只需要封裝如下一個工具類就行了:
public class UrlUtil { private static Properties config = null; static { InputStream in = UrlUtil.class.getClassLoader().getResourceAsStream("url.properties"); config = new Properties(); try { config.load(in); in.close(); } catch (IOException e) { //讀取url.properties出錯 e.printStackTrace(); } } /** * 通過鍵獲得對應的值 * @param key * @return */ public static String getValue(String key) { try { String value = config.getProperty(key); return value.trim(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 讀取properties的全部信息*/ public static void getAllProperties() { try { Enumeration en = config.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String Property = config.getProperty(key); } } catch (Exception e) { e.printStackTrace(); System.err.println("ConfigInfoError" + e.toString()); } } public static void main(String args[]) { }}代碼中的url.properties就是我們放置路徑的配置文件。比如我們的url.properties中有個圖片路徑:imgPath=c:/images
我們要取得這個值只需要使用:UrlUtil.getValue("imgPath")就行了。
新聞熱點
疑難解答