Java程序读取配置文件的几种方法

Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易。

1. 读取properties文件的方法

1. 使用类加载器ClassLoder类读取配置文件

  • InputStream in = MainClass.class.getClassLoader().getResourceAsStream("com/demo/config.properties");

    • MainClass.class是主类的反射对象,因为getClassLoader()是class类的对象方法。
    • 在类加载器中调用getResourceAsStream()时,采用相对路径,起始位置在src目录,路径开头没有“/”。
  • InputStream in = (new MainClass()).getClass().getClassLoader().getResourceAsStream("com/demo/config.properties");

    • 因为getClass()是object类的对象方法,所有在主类调用时要将主类实体化,即new MainClass()。
    • 同理,相对路径起始位置同上。

2. 用class对象读取配置文件

之所以Class对象也可以加载资源文件是因为Class类封装的getResourceAsStream方法的源码中调用了类加载器。

  • InputStream in = MainClass.class.getResourceAsStream(“/com/demo/config.properties”);

    • 同样MainClass.class是主类的反射对象。
    • 在class对象中调用getResourceAsStream()时,采用绝对路径,起始位置在类路径(bin目录),因此路径要以“/”开头。
  • InputStream in = MainClass.class.getResourceAsStream(“config.properties”);

    • 这种写法是指文件与源码在同一个目录,class对象会在本目录找文件。

3. 使用 BufferedReader输入流读取配置文件

  • 这种方式只能是结对路径,可以读取任意路径下的配置文件:

    Properties prop = new Properties();
    FileReader reader = new FileReader("E:/config.properties");
    BufferedReader bufferedReader = new BufferedReader(reader);
    prop.load(bufferedReader);
    
  • 可以使用System.getProperty("user.dir")方法获取当前程序运行的工作根目录,动态调整路径:

    String rootPath = System.getProperty("user.dir");
    FileReader reader = new FileReader(rootPath +"/com/demo/config.properties");
    

4. 使用ResourceBundle类读取配置信息

  • java.util.ResourceBundle 类中的静态方法getBundle("path")读取一个配置文件,必须是 .propertise文件,所有不用写后缀。
  • ResourceBundle对象只能每个参数读取,需要使用集合来批处理。
  • 采用相对路径,起始位置在src目录,路径开头不需要“/”
ResourceBundle resource = ResourceBundle.getBundle("com/demo/config");
String paraValue = resource.getString("paramName");

Java程序读取配置文件的几种方法

上一篇:iMazing iOS for mac设备管理软件V2021


下一篇:基于Python包生成PDF文件之Reportlab的Platypus生成表格和图片的方法