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.
Check everything carefully
Here's a list to work through:
jaskeyfile.3DES
is located in src/main/resources
within the spr-resources module 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.