.properties文件的使用

方法1:

 

 

 

 

/** * 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
    }

 

 

方法2:

在不少项目中咱们都会使用到.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"));
相关文章
相关标签/搜索