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,但是这里有一些方法可以在类路径中添加目录:
- Intelli J : how to add directory to classpath in an application run profile in intellij idea?
- Eclipse : How do I add a directory to the eclipse classpath?
- At run time : Can a directory be added to the class path at runtime?
- At command line : http://javarevisited.blogspot.com/2012/10/5-ways-to-add-multiple-jar-to-classpath-java.html
Intelli J:如何在intellij idea中的应用程序运行配置文件中将目录添加到类路径?
Eclipse:如何将目录添加到eclipse类路径?
在运行时:可以在运行时将目录添加到类路径吗?
在命令行:http://javarevisited.blogspot.com/2012/10/5-ways-to-add-multiple-jar-to-classpath-java.html
#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,但是这里有一些方法可以在类路径中添加目录:
- Intelli J : how to add directory to classpath in an application run profile in intellij idea?
- Eclipse : How do I add a directory to the eclipse classpath?
- At run time : Can a directory be added to the class path at runtime?
- At command line : http://javarevisited.blogspot.com/2012/10/5-ways-to-add-multiple-jar-to-classpath-java.html
Intelli J:如何在intellij idea中的应用程序运行配置文件中将目录添加到类路径?
Eclipse:如何将目录添加到eclipse类路径?
在运行时:可以在运行时将目录添加到类路径吗?
在命令行:http://javarevisited.blogspot.com/2012/10/5-ways-to-add-multiple-jar-to-classpath-java.html
#2
0
InputStream resourceStream =
getClass().getResourceAsStream("/package/folder/foo.properties");
Try above code.
试试上面的代码。
Hope this will helps.
希望这会有所帮助。