0

I have a simple Maven project where in one of my test, I would like to load a resource as a csv file from the resources folder. The resources folder is made available under src/test/resources

When I run the following code snippet:

URL url = getClass()
        .getClassLoader()
        .getResource("/myData.csv");
System.out.println(this.getClass().getResource("."));
System.out.print(url); // this gives null

I get a null for the url! Here is my build file:

<build>
    <resources>
        <resource>
            <directory>src/test/resources</directory>
            <includes>
                <include>*.csv</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>${target.jdk}</source>
                <target>${target.jdk}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Why is this not working? I'm on IntelliJ!

Tunaki
  • 132,869
  • 46
  • 340
  • 423
joesan
  • 13,963
  • 27
  • 95
  • 232
  • Remove completely your `` block, you don't need it. Second, you should use an `InputStream`: `getClass().getResourceAsStream(/myData.csv)` – Tunaki May 26 '16 at 23:45

1 Answers1

0

When loading resources via ClassLoader (as opposed to Class), you don't need to use absolute URLs, so just remove the leading slash /.

For details, see https://stackoverflow.com/a/6608848/2492865

Community
  • 1
  • 1
Anton Koscejev
  • 4,603
  • 1
  • 21
  • 26
  • Also note that by default Maven includes everything under `src/main/resources` as resources and `src/test/resources` as test resources (only available during test and integration-test phases. You're overriding main resources to point to test resources, which is highly suspicious. – Anton Koscejev May 27 '16 at 08:08