I have a nasty problem referencing resources when using a Maven project and Jar files…
I have all my resources in a dedicated folder /src/main/resources which is part of the build path in Eclipse. Files are referenced using
getClass().getResource("/filename.txt")
This works fine in Eclipse but fails in the Jar file – there the resources are located in a folder directly below the jar’s root…
Does anyone know a ‘best practice’ to reference a file both in the JAR and (!) in Eclipse?
Edit:
The problem is that while the resources actually are located in the JAR in a folder “resources” at the top level, the above method fails to find the file…
The contents of Maven resource folders are copied to target/classes and from there to the root of the resulting Jar file. That is the expected behaviour.
What I don’t understand is what the problem is in your scenario. Referencing a Resource through
getClass().getResource("/filename.txt")starts at the root of the classpath, whether that (or an element of it) istarget/classesor the JAR’s root. The only possible error I see is that you are using the wrongClassLoader.Make sure that the class that uses the resource is in the same artifact (JAR) as the resource and do
ThatClass.class.getResource("/path/with/slash")orThatClass.class.getClassLoader().getResource("path/without/slash").But apart from that: if it isn’t working, you are probably doing something wrong somewhere in the build process. Can you verify that the resource is in the JAR?