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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:24:05  来源:igfitidea点击:

Java: How do I open a text file in test that is in src/main/resources?

java

提问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 resourcesdirectory is a source folder, you can use /resources/definitions.txtas a correct path.

如果您的resources目录是源文件夹,则可以/resources/definitions.txt用作正确的路径。

I don't know about ResourceServicebut this should work:

我不知道,ResourceService但这应该有效:

final Properties definitions = new Properties();
definitions.load(getClass().getResourceAsStream("/resources/definitions.txt"))