如何从Java中的资源目录加载文件

时间:2023-02-06 13:16:50

I am trying to load a properties file directly from the resources directory of my Java project and am getting a null pointer exception. Can someone pl explain how to do it?

我试图直接从我的Java项目的资源目录加载属性文件,并获得空指针异常。有人可以解释怎么做吗?

Code-

String resourceName = "config-values.properties"; 
Properties props = new Properties();
try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourceName)) {
            props.load(resourceStream);
        }

My folder structure is - /src/packageName and /src/resources/

我的文件夹结构是 - / src / packageName和/ src / resources /

2 个解决方案

#1


2  

Following code expects that the resource, you are trying to access, exists in your class path.

以下代码期望您尝试访问的资源存在于类路径中。

getClassLoader().getResourceAsStream(resourceName))

Assuming that your file exists in src/resources: You may add src/resources/ in your classpath. I don't know which IDE are you using but here are some ways to add a directory in the classpath:

假设您的文件存在于src / resources中:您可以在类路径中添加src / resources /。我不知道你使用的是哪个IDE,但是这里有一些方法可以在类路径中添加目录:

#2


0  

InputStream resourceStream  = 
 getClass().getResourceAsStream("/package/folder/foo.properties");

Try above code.

试试上面的代码。

Hope this will helps.

希望这会有所帮助。

#1


2  

Following code expects that the resource, you are trying to access, exists in your class path.

以下代码期望您尝试访问的资源存在于类路径中。

getClassLoader().getResourceAsStream(resourceName))

Assuming that your file exists in src/resources: You may add src/resources/ in your classpath. I don't know which IDE are you using but here are some ways to add a directory in the classpath:

假设您的文件存在于src / resources中:您可以在类路径中添加src / resources /。我不知道你使用的是哪个IDE,但是这里有一些方法可以在类路径中添加目录:

#2


0  

InputStream resourceStream  = 
 getClass().getResourceAsStream("/package/folder/foo.properties");

Try above code.

试试上面的代码。

Hope this will helps.

希望这会有所帮助。