我的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)
答案 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.java
和application.properties
都在不同的包中。
要么
将application.properties
从com.philips.rs.properties
移至com.philips.rs.utils
并直接阅读。
String filename = "application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);
或者将filename
更改为"/com/philips/rs/properties/application.properties"
String filename = "/com/philips/rs/properties/application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);
更好的解释可以从https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-
找到