类加载器的getResourceAsStream方法返回null。

30

我的项目目录结构(在Eclipse中):

MyProject/
    src/        --> "source directory" on Eclipse's classpath/buildpath
        com.me.myapp
            Driver
            myconfig.txt

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 :-)");
    }
}

当我运行这个程序时,会在控制台输出以下内容:
input stream is null

为什么会把myconfig.txt放错位置了?是我错误地使用了ClassLoader API吗?还是其他原因?
3个回答

45

如果它在同一个包中,请使用

InputStream is = Driver.class.getResourceAsStream("myconfig.txt");

你目前的方式

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("myconfig.txt");

它正在根据类路径查找文件。您可以使用

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("com/me/myapp/myconfig.txt");

搜索规则在ClassLoader#getResource(String)javadocClass#getResource(String)javadoc中有详细说明。


10

如果你正在使用Maven,将以下行添加到BUILD标签下。当你在服务器上运行Web应用程序但没有引用服务器上的资源时,会出现这个错误。

因此,将以下内容添加到你的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>

玩得开心.!!!


0
  • 使用-

    InputStream is = ClassLoader.getSystemClassLoader.getResourceAsStream("com/me/myapp/myconfig.txt");

  • 替代-

    InputStream is = ClassLoader.getSystemClassLoader.getResourceAsStream("myconfig.txt");

  • 注意:不需要在包名前提供源文件夹名称(src)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接