用过的这些方法—读取properties配置文件

代码写得多了,对于同一功能的代码也会遇到多种实现,权且记录一下。

  读取properties文件

  1.使用ResourceBundle加载

    ResourceBundle bundle = ResourceBundle.getBundle("MyResource",Locale.getDefault()); //读取工程类路径下的 MyResource.properties文件,当然也可以为其他名字,例如:conf.properties
    String name = bundle.getString("name"); 
    System.out.println(name);

  2.使用Properties加载

     Properties prop = new Properties();
   prop.load(new FileInputStream(new File("conf/config.properties")));  //注意:此方法加载文件路径
   //
prop.load(XX.class.getClassLoader().getResourceAsStream("conf.properties"))); //注意:此方法读取工程类路径下 的conf.properties文件
   String name = prop.getProperty("name");
   System.out.println(name);

  注意:简单测试了一下,上面两种方式效率类似

  3.自己来解析文件,读取配置,代码暂略吧..闲了再写

原文地址:https://www.cnblogs.com/baby-bear/p/4005124.html