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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:34:34  来源:igfitidea点击:

ClassLoader getResourceAsStream returns null

javaeclipseclasspathclassloaderinputstream

提问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.txtin 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.!!!

玩得开心。!!!