項目中將一些變量配置到properties資源文件中,能夠起到方便修改的做用,這裏能夠用PropertiesUtil工具類進行讀取文件內容。java
import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class PropertiesUtil { public static Map<String, String> loadProperties(String path) { Map<String, String> map = new HashMap<String, String>(); InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);//資源文件與classpath的相對路徑 // InputStream in = Test2.class.getResourceAsStream(path);//資源文件與PropertiesUtil的相對路徑 if(null==in){ return map; } try { Properties pros = new Properties(); pros.load(in); Enumeration en = pros.propertyNames();// 獲得資源文件中的全部key值 while (en.hasMoreElements()) { String key = (String) en.nextElement(); map.put(key, pros.getProperty(key)); } return map; } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("關閉流失敗"); } } return map; } }