简体   繁体   中英

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:

  1. The file jaskeyfile.3DES is located in src/main/resources within the spr-resources module
  2. Your local repository contains the latest version of spr-resources-xyz-SNAPSHOT.jar (or you've released it/versioned it directly) and you've definitely used mvn clean install on it
  3. The spr-common module is referencing the correct (named) version of spr-resources-xyzjar (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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM