Reputation: 27476
I'm using maven 2.1.0 and have a project with multiple modules. Example modules:
spr-common has a dependency on spr-resources
spr-resources contains only files, no classes.
spr-common has a junit in which needs to load a file from spr-resources jar.
I used:
String fileName = getClass().getResource("/jaskeyfile.3DES").getFile();
is = getClass().getClassLoader().getResourceAsStream(fileName);
is.read(data);
And this works when I run the test in IntelliJ, but when I do mvn test, it fails with NullPointerException when I try to do read() on it.
Why is this happening? It should read a file from dependency just fine.
Also, pom.xml in spr-common has dependency on spr-resources (tried both with scope test and without it)
EDIT: I tried also
getClass().getClassLoader().getResourceAsStream("/jaskeyfile.3DES");
with no luck.
EDIT2: The given file exists in the resulting jar, so I guess it should be accessible.
Upvotes: 4
Views: 6291
Reputation: 716
I believe the issue may be with the leading slash. I think both of these should work:
getClass().getResourceAsStream("/jaskeyfile.3DES")
getClass().getClassLoader().getResourceAsStream("jaskeyfile.3DES")
Class.getResourceAsStream()
takes a path relative to the class's package directory so it accepts the leading slash.
ClassLoader.getResourceAsStream()
takes an absolute path already so it doesn't accept the leading slash.
Upvotes: 2
Reputation: 7257
Check everything carefully
Here's a list to work through:
jaskeyfile.3DES
is located in src/main/resources
within the spr-resources moduleIf all the above are true then your getClass().getResourceAsStream("/jaskeyfile.3DES")
invocation should work. I use this structure all the time in my projects so you're not asking for the moon or anything here.
Upvotes: 3