Java:如何在测试中打开 src/main/resources 中的文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13074051/
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: How do I open a text file in test that is in src/main/resources?
提问by daydreamer
my project struture looks like
我的项目结构看起来像
project/
src/main/
java/ ...
resources/
definitions.txt
test/
CurrentTest.java
resources/ ...
In my test I need to open the definitions.txt
在我的测试中,我需要打开 definitions.txt
I do
我做
@Test
public void testReadDesiredDefinitions() throws PersistenceException, IOException {
final Properties definitions = new Properties();
definitions.load(new ResourceService("/").getStream("desiredDefinitions"));
System.out.println(definitions);
}
When I run this, I get
当我运行这个时,我得到
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
How can I read this text file?
我怎样才能阅读这个文本文件?
Thanks
谢谢
回答by Bohemian
The "current directory" of unit tests is usually the project directory, so use this:
单元测试的“当前目录”通常是项目目录,所以使用这个:
File file = new File("src/main/resources/definitions.txt");
and load the properties from the file:
并从文件加载属性:
definitions.load(new FileInputStream(file));
If this doesn't work, or you want to check what the current directory is, just print out the path and it will be obvious what the current directory is:
如果这不起作用,或者您想检查当前目录是什么,只需打印出路径,就会很明显当前目录是什么:
System.out.println(file.getAbsolutePath());
回答by FThompson
You can make use of Class#getResourceAsStreamto easily create a stream to a resource file.
您可以使用Class#getResourceAsStream轻松创建到资源文件的流。
definitions.load(getClass().getResourceAsStream("/main/java/resources/definitions.txt"));
The location parameter should be the relative file path with regards to your project base (my guess was main).
location 参数应该是与您的项目库相关的相对文件路径(我的猜测是主要的)。
回答by tux23
File file = new File("../src/main/resources/definitions.txt");
File file = new File("../src/main/resources/definitions.txt");
回答by Alex
If your resources
directory is a source folder, you can use /resources/definitions.txt
as a correct path.
如果您的resources
目录是源文件夹,则可以/resources/definitions.txt
用作正确的路径。
I don't know about ResourceService
but this should work:
我不知道,ResourceService
但这应该有效:
final Properties definitions = new Properties();
definitions.load(getClass().getResourceAsStream("/resources/definitions.txt"))