Java在项目文件夹中获取文件作为资源

时间:2013-08-22 16:58:37

标签: java io

我目前在Java中设置了一个项目,在Eclipse中使用以下目录结构:

enter image description here

在我的代码中,我有以下几行:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

但是,InputStream is总是被赋值为null,这会在到达第二行时导致崩溃。我知道这与我如何设置它正在寻找的路径有关,但我无法弄清楚它为什么不起作用。

2 个答案:

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

在这两种情况下,请务必在“资源”

之前加上“/”