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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42779395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:52:02  来源:igfitidea点击:

How to load file from resources directory in Java

java

提问by AP01

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/

回答by

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,但这里有一些在类路径中添加目录的方法:

回答by Sagar Gangwal

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

Try above code.

试试上面的代码。

Hope this will helps.

希望这会有所帮助。

回答by gorbysbm

Adding another way to do it without stream

添加另一种没有流的方法

File ourFile = new File(getClass().getClassLoader().getResource("yourFile.txt").getFile());

and then you can do things like

然后你可以做这样的事情

ourFile.getAbsolutePath()