Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 708
daydreamer Avatar asked Oct 25 '12 17:10

daydreamer


2 Answers

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());
like image 102
Bohemian Avatar answered Sep 19 '22 06:09

Bohemian


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

like image 27
FThompson Avatar answered Sep 23 '22 06:09

FThompson