Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取maven中src/test/resource下包中的属性文件_Java_Maven_Properties_Nullpointerexception_File Handling - Fatal编程技术网

Java 读取maven中src/test/resource下包中的属性文件

Java 读取maven中src/test/resource下包中的属性文件,java,maven,properties,nullpointerexception,file-handling,Java,Maven,Properties,Nullpointerexception,File Handling,我的maven结构如下所示: 已将属性文件放在包中的src/test/resources下 我试图读取src/Test/java下的java类(浏览器测试) 我使用下面的代码来准备文件,但是获取NullPointerException public Static Properties CONFIG CONFIG = new Properties(); InputStream inputStream = BrowserTest.class.getResourceAsStream(filename

我的maven结构如下所示:

已将属性文件放在包中的src/test/resources下 我试图读取src/Test/java下的java类(浏览器测试)

我使用下面的代码来准备文件,但是获取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)

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

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

您将获得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);
    
  • 或者将
    文件名更改为
    “/com/philips/rs/properties/application.properties”

  • 更好的解释可以从

    String filename = "/com/philips/rs/properties/application.properties";
    InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
    CONFIG.load(inputStream);