[英]Loading a file from dependency jar inside maven junit
I'm using maven 2.1.0 and have a project with multiple modules. 我正在使用maven 2.1.0并且有一个包含多个模块的项目。 Example modules: 示例模块:
spr-common has a dependency on spr-resources spr-common依赖于spr资源
spr-resources contains only files, no classes. spr-resources只包含文件,没有类。
spr-common has a junit in which needs to load a file from spr-resources jar. spr-common有一个junit,需要从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. 这在我在IntelliJ中运行测试时有效,但是当我进行mvn测试时,当我尝试对其执行read()时,它会因NullPointerException而失败。
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) 另外,spr-common中的pom.xml依赖于spr-resources(尝试使用范围测试,没有使用它)
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. EDIT2:给定的文件存在于生成的jar中,所以我想它应该是可访问的。
Check everything carefully 仔细检查一切
Here's a list to work through: 这是一个可以解决的列表:
jaskeyfile.3DES
is located in src/main/resources
within the spr-resources module 文件jaskeyfile.3DES
位于spr-resources模块中的src/main/resources
中 If all the above are true then your getClass().getResourceAsStream("/jaskeyfile.3DES")
invocation should work. 如果以上所有都是真的那么你的getClass().getResourceAsStream("/jaskeyfile.3DES")
调用应该工作。 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. Class.getResourceAsStream()
接受相对于类的包目录的路径,因此它接受前导斜杠。
ClassLoader.getResourceAsStream()
takes an absolute path already so it doesn't accept the leading slash. ClassLoader.getResourceAsStream()
已经采用绝对路径,因此它不接受前导斜杠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.