读取位于maven中src / test / resource下的包内的属性文件

时间:2017-07-05 02:50:15

标签: java maven properties nullpointerexception file-handling

我的maven结构如下所示:

已将属性文件放在src / test / resources下的包中 我试图从src / test / java

下的java类(Browser Test)中读取

我使用下面的代码来准备文件,但是获取NullPointerException。

public Static Properties CONFIG 
CONFIG = new Properties();
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);


[31mMessage: [0m[31mjava.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)

enter image description here

2 个答案:

答案 0 :(得分:1)

将资源文件放在src/test/resources树(src/test/resources/application.properties)的根目录中。然后使用static初始化块。像,

public static Properties CONFIG = new Properties();
static {
    try {
        CONFIG.load(BrowserTest.class.getResourceAsStream(
                "application.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

您收到NullPointerException,因为BrowserTest.javaapplication.properties都在不同的包中。

要么

  1. application.propertiescom.philips.rs.properties移至com.philips.rs.utils并直接阅读。

    String filename = "application.properties";
    InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
    CONFIG.load(inputStream);
    
  2. 或者将filename更改为"/com/philips/rs/properties/application.properties"

    String filename = "/com/philips/rs/properties/application.properties";
    InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
    CONFIG.load(inputStream);
    
  3. 更好的解释可以从https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-

    找到