daydreamer
daydreamer

Reputation: 91949

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

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

Upvotes: 12

Views: 11166

Answers (4)

Bohemian
Bohemian

Reputation: 425033

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

Upvotes: 14

tux23
tux23

Reputation: 225

File file = new File("../src/main/resources/definitions.txt");

Upvotes: 0

FThompson
FThompson

Reputation: 28687

You can make use of Class#getResourceAsStream to easily create a stream to a resource file.

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

Upvotes: 1

Alex
Alex

Reputation: 25613

If your resources directory is a source folder, you can use /resources/definitions.txt as a correct path.

I don't know about ResourceService but this should work:

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

Upvotes: 0

Related Questions