简体   繁体   English

Java:如何在src / main / resources中的test中打开文本文件?

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

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 谢谢

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());

You can make use of Class#getResourceAsStream to 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参数应该是与项目库有关的相对文件路径(我的猜测是主要的)。

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"))

文件文件=新文件(“../ src / main / resources / definitions.txt”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM