Loading a file from dependency jar inside maven junit
I'm using maven 2.1.0 and have a project with multiple modules. Example modules:
- spr-resources
- spr-common
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.
Check everything carefully
Here's a list to work through:
- The file
jaskeyfile.3DES
is located insrc/main/resources
within the spr-resources module - Your local repository contains the latest version of spr-resources-x.y.z-SNAPSHOT.jar (or you've released it/versioned it directly) and you've definitely used mvn clean install on it
- The spr-common module is referencing the correct (named) version of spr-resources-x.y.z.jar (scope of compile will be seen on both test and compile classpaths)
If 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.
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.
精彩评论