Java在项目文件夹中获取文件作为资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18386613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java getting file as resource when it's in the project folder
提问by Giardino
I currently have a project in Java set up with the following directory structure in Eclipse:
我目前有一个 Java 项目,在 Eclipse 中设置了以下目录结构:
And in my code I have the following lines:
在我的代码中,我有以下几行:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
However, the InputStream is
always gets assigned to null, which causes a crash when it gets to the second line. I know it has something to do with how I set up the path that it's looking for, but I can't figure out exactly why it isn't working.
然而,InputStream is
总是被分配给空值,当它到达第二行时会导致崩溃。我知道这与我如何设置它正在寻找的路径有关,但我无法弄清楚它为什么不起作用。
采纳答案by Sotirios Delimanolis
Your config
file is in your project, somewhere on the file system.
您的config
文件在您的项目中,位于文件系统的某个位置。
However, Eclipse isn't putting it on the classpath. To force it to be on the classpath, right click your folder and add it as a source folder. Eclipse will then add it to the root of the classpath. You can retrieve it with
但是,Eclipse 并没有将它放在类路径上。要强制它在类路径上,请右键单击您的文件夹并将其添加为源文件夹。Eclipse 然后会将它添加到类路径的根目录中。你可以用
InputStream is = this.getClass().getResourceAsStream("/config");
Eclipse puts everything in resources
source folder starting at the root of the classpath. Therefore
Eclipse 将所有内容放在resources
从类路径的根目录开始的源文件夹中。所以
resources/config
resources/config
will appear in classpath as
将出现在类路径中
/config
/qbooksprintfix/FileChecker
/qbooksprintfxi/FilePurgeHandler
/...
回答by Abstract
Try whit InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();
试试白 InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();
or InputStream is = this.getClass().getClassLoader().getResourceAsStream("/resources/config");
或者 InputStream is = this.getClass().getClassLoader().getResourceAsStream("/resources/config");
In both cases make sure to put "/" before the "resources"
在这两种情况下,请确保将“/”放在“资源”之前