1

I have a junit testcase and a file that I want to load during that test. The file is placed under src/main/resources, whereas the packages are named same as the java testfile:

src/test/java/my/path/to/FileTest.java
src/test/resource/my/path/to/test.txt

Usage:

public class FileTest {
    @Test
    public void testRead() {
        String content = IOUtils.toString(this.getClass().getResourceAsStream("test.txt"), Charset.defaultCharset());
        System.out.println(content);
    }
}

Exception when running the testcase in IDE:

java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:113)
    at org.apache.commons.io.IOUtils.copy(IOUtils.java:2272)
    at org.apache.commons.io.IOUtils.toString(IOUtils.java:1041)

What might be wrong here?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • did you see https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null?* –  May 29 '17 at 10:48
  • have to tried getResourceAsStream("/my/path/to/test.txt")? – Ori Marko May 29 '17 at 10:48
  • @user7294900 yes but I'd like to prevent having to define the fully qualified package path. – membersound May 29 '17 at 10:54
  • @RC. yes but also `FileTest.class.getResourcAsStream("test.txt");` fails with NPE. – membersound May 29 '17 at 10:56
  • It should be `System.out.println(new BufferedReader(new FileReader(this.getClass().getClassLoader().getResource("my/path/to/test.txt").getFile())).readLine());` **without** the leading `/`, or `System.out.println(new BufferedReader(new FileReader(this.getClass().getResource("/my/path/to/source.txt").getFile())).readLine());` **with** the leading `/`. BTW using java 8 here. – Morfic May 29 '17 at 12:38
  • have you tried new String(Files.readAllBytes(Paths.get(this.getClass().getResource("test.txt").getFile()))) ? – Ilya Zinkovich May 29 '17 at 17:49
  • @IlyaZinkovich gives also a NPE. – membersound May 30 '17 at 06:49
  • I take it my suggestion somehow also failed? If so, could you please share a [sscce](http://sscce.org) on github or something similar? I'm interested in this since on my end it worked fine. – Morfic May 31 '17 at 13:38
  • @Morfic of course your solution works, **but** I'm looking for a solution where I don't have to provide the fully qualified package path (my/path/to). – membersound May 31 '17 at 13:48
  • I see, sorry I missed that part. Then how about the following ugly hack: `this.getClass().getClassLoader().getResource(this.getClass().getPackage().getName().replace(".", "/") + "/" + "test.txt"`)? – Morfic May 31 '17 at 14:00

1 Answers1

0

I ended placing the testfiles directly into /src/main/resources without subpackage, and using.

PropertiesLoaderUtils.loadProperties(new ClassPathResource(filename));

membersound
  • 81,582
  • 193
  • 585
  • 1,120