/** * ResourceBundle: * 1.能夠用於讀取properties文件; * 2.只能讀取不能寫入 * 3.只能讀取類路徑下的,不在類路徑下的沒法讀取 * */ private static ResourceBundle resourceBundle=ResourceBundle.getBundle("config.bean");//參數指的是properties文件的位置,寫法是包名.文件名的方式 public static void main(String[] args) { System.err.println(resourceBundle.getString("ACCOUNTERVICE"));//com.luzhanshi.learn.service.impl.IAccountServiceImplImpl }
在不少項目中咱們都會使用到.properties文件對咱們的項目進行配置,今天就介紹一下.properties文件在項目中的使用:工具
以下圖,咱們項目中有一個名爲project.properties的properties文件 spa
從圖中能夠看出,該文件配置了許多參數的默認值,那麼咱們在項目中如何引用它呢?:code
首先咱們書寫一個工具類ProjectUtils:blog
/** * 傳入配置文件路徑,將其中屬性映射到Map中 * * @param filepath * @return map */ public Map<String, String> getPropertiesValueMap(String filepath) { InputStreamReader isr = null; logger.info("接收到配置文件路徑是 filepath + " +filepath); Map<String, String> properties = new HashMap<>(); if ("".equals(filepath)) { logger.info("傳入配置文件路徑不能爲空!!"); return properties; } try { Properties pro = new Properties(); isr = new InputStreamReader(getClass().getClassLoader() .getResourceAsStream(filepath),"UTF-8"); pro.load(isr); @SuppressWarnings("rawtypes") Enumeration enu = pro.propertyNames(); while (enu.hasMoreElements()) { String obj =(String) enu.nextElement(); String objv = pro.getProperty(obj); properties.put(obj, objv); } } catch (Exception e) { properties.put("retCode","01"); properties.put("retMsg","讀取配置文件失敗,請檢查配置文件"); logger.info("解析配置文件失敗,請檢查配置文件是否正確!!,緣由是:"+e.getMessage()); return properties; } return properties; }
而後在須要獲取配置信息的地方調用上面咱們封裝的方法(傳入配置文件的路徑):get
ProjectUtils pro = new ProjectUtils(); Map<String ,String> map = pro.getPropertiesValueMap("project.properties"); //System.out.println(map.get("440600")); int port =Integer.valueOf(map.get("port")); System.out.println(map.get("port"));