ClassLoader getResourceAsStream返回null [英] ClassLoader getResourceAsStream returns null

查看:257
本文介绍了ClassLoader getResourceAsStream返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My project directory structure (in Eclipse):

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

驱动程序中,我有以下代码:

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

为什么?有没有将 myconfig.txt 放在不正确的位置?我正在使用ClassLoader API吗?还有什么?感谢提前!

Why? Have I placed myconfig.txt in an incorrect location? Am I using the ClassLoader API incorrectly? Something else? Thanks in advance!

推荐答案

如果它在同一个包中使用

If it's in the same package use

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

您的方式

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

搜索规则在 javadoc of ClassLoader#getResource(String) javadoc of Class#getResource(String)

The rules for searching are explained in the javadoc of ClassLoader#getResource(String) and the javadoc of Class#getResource(String).

这篇关于ClassLoader getResourceAsStream返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆