我目前在Java中设置了一个项目,在Eclipse中使用以下目录结构:
在我的代码中,我有以下几行:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
但是,InputStream is
总是被赋值为null,这会在到达第二行时导致崩溃。我知道这与我如何设置它正在寻找的路径有关,但我无法弄清楚它为什么不起作用。
答案 0 :(得分:9)
您的config
文件位于项目中,位于文件系统的某个位置。
但是,Eclipse并没有将它放在类路径上。要强制它在类路径上,请右键单击您的文件夹并将其添加为源文件夹。 Eclipse然后将它添加到类路径的根目录。您可以使用
检索它InputStream is = this.getClass().getResourceAsStream("/config");
Eclipse将所有内容放在resources
源文件夹中,从类路径的根开始。因此
resources/config
将在类路径中显示为
/config
/qbooksprintfix/FileChecker
/qbooksprintfxi/FilePurgeHandler
/...
答案 1 :(得分:0)
尝试使用InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();
或InputStream is = this.getClass().getClassLoader().getResourceAsStream("/resources/config");
在这两种情况下,请务必在“资源”
之前加上“/”