Can't access to files in resources directory with Maven (with Eclipse IDE)

It looks to me like your problem is

File testf = new File( "/test.txt" );

That's looking for a file called test.txt at the root of your computer's filesystem. What you want is the root of the resource tree, which you get with the getResource method:

File testf = new File( this.getClass().getResource( "/test.txt" ).toURI() );

Or, in static context, use the name of the containing class:

File testf = new File( MyClass.class.getResource( "/test.txt" ).toURI() );

Of course you'll need to add error handling to that example.


I had the same problem, just make sure that the "text.txt" file is in the resources folder of the test project (src/test/resources/text.txt) and not in any other resources folder. Also, you should retrieve the file from the resources folder like this:

this.getClass().getClassLoader().getResource("text.txt").getFile();

If this still does not work then try to set the useSystemClassLoader from the maven-surefire-plugin to false in your pom.xml.

http://maven.apache.org/surefire/maven-surefire-plugin/examples/class-loading.html


Check your <build> tag in pom.xml it should be something like this, faced the same issue and adding this <resources> tag in the <build> worked for me.

<build>
    <resources>
        <resource>
            <filtering>true</filtering>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>