Java ClassLoader getResourceAsStream 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19035407/
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
ClassLoader getResourceAsStream returns null
提问by IAmYourFaja
My project directory structure (in Eclipse):
我的项目目录结构(在 Eclipse 中):
MyProject/
src/ --> "source directory" on Eclipse's classpath/buildpath
com.me.myapp
Driver
myconfig.txt
In Driver
, I have the following code:
在Driver
,我有以下代码:
public class Driver {
public static void main(String[] args) {
InputStream is = ClassLoader.getSystemClassLoader.getResourceAsStream("myconfig.txt");
if(is == null)
System.out.println("input stream is null");
else
System.out.println("input stream is NOT null :-)");
}
}
When I run this I get the following console output:
当我运行它时,我得到以下控制台输出:
input stream is null
Why?Have I placed myconfig.txt
in an incorrect location? Am I using the ClassLoader API incorrectly? Something else? Thanks in advance!
为什么?我是否放置myconfig.txt
在错误的位置?我是否错误地使用了 ClassLoader API?还有什么?提前致谢!
采纳答案by Sotirios Delimanolis
If it's in the same package use
如果它在同一个包中使用
InputStream is = Driver.class.getResourceAsStream("myconfig.txt");
The way you have it
你拥有它的方式
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("myconfig.txt");
It's looking for the file in the root of the classpath. You could use
它正在类路径的根目录中查找文件。你可以用
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("com/me/myapp/myconfig.txt");
The rules for searching are explained in the javadoc of ClassLoader#getResource(String)
and the javadoc of Class#getResource(String)
.
搜索规则在javadoc ofClassLoader#getResource(String)
和javadoc ofClass#getResource(String)
中解释。
回答by Hitesh
If you are working with Maven, add the following lines under BUILDtag. You get this error when you are running the webapp on server but there is no reference to the resources on the server.
如果您正在使用 Maven,请在BUILD标记下添加以下行。当您在服务器上运行 web 应用程序但没有引用服务器上的资源时,您会收到此错误。
So, add this the following into your POM.xml and see the magic.
因此,将以下内容添加到您的 POM.xml 中并查看魔法。
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>fileName.txt</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>fileName.wsdl</include>
</includes>
</resource>
</resources>
Have Fun.!!!
玩得开心。!!!