我的项目目录结构(在 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?还有别的吗?
原文由 IAmYourFaja 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果它在同一个包中使用
你拥有它的方式
它在类路径的根目录中寻找文件。你可以使用
搜索规则在
ClassLoader#getResource(String)
的Class#getResource(String)
中进行了解释。