Onejar和资源加载 [英] Onejar and resource loading
问题描述
我有一个Maven项目,我想将其打包到一个可执行jar中. 它使用了很多依赖项,例如spring等. 在一些帖子中建议使用OneJar,以避免造成很多麻烦. 这是我目前在pom.xml中所拥有的:
I have a maven project which I would like to package in an executable jar. It's using quite a few dependencies, like spring and so on. It was suggested in a few posts to use OneJar, to avoid a lot of headaches. This is what I have currently in my pom.xml:
<plugin>
<groupId>org.dstovall</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>1.4.4</version>
<executions>
<execution>
<configuration>
<mainClass>com.cool.project.Application</mainClass>
<onejarVersion>0.97</onejarVersion>
<attachToBuild>true</attachToBuild>
<classifier>coolproject</classifier>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
在我的Spring配置中,其中一个类需要将资源(src/main/resources/coolfile.bin
)路径传递给外部库(jsch)方法:
In my Spring configuration one of the classes needs to pass the a resource (src/main/resources/coolfile.bin
) path to an external library (jsch) method:
String resource = ConfigurationClass.class.getClassLoader().getResource("coolfile.bin").getFile();
jsch.addIdentity(resource);
当我从IDE(Eclipse)运行Application.java
时,整个应用程序成功加载.
When I run Application.java
from the IDE (eclipse), the entire application loads successfully.
尽管当我运行mvn clean install
时,onejar jar是在target
文件夹下构建的,但是当我尝试使用java -jar coolproject.one-jar.jar
运行它时,会显示以下错误:
Although when I run mvn clean install
, the onejar jar is built under the target
folder, but when I try to run it with java -jar coolproject.one-jar.jar
the following error is displayed:
...
Caused by: java.io.FileNotFoundException: file:/target/coolproject.one-jar.jar!/main/coolproject.jar!/coolfile.bin (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:83
如果我检查coolproject.one-jar.jar
,则可以在main
文件夹下找到coolproject.jar
,如果我检查了它,则可以在其根目录中看到coolfile.bin
.
If I inspect coolproject.one-jar.jar
, I can find the coolproject.jar
under the main
folder, and if I inspect that, I can see coolfile.bin
in its root.
因此,从理论上讲应该找到资源?我想念什么?
So in theory the resource should be found? What am I missing?
推荐答案
事实证明,FileInputStream
找不到由resource
指定的路径.
幸运的是,jsch
提供了另一种方法,您可以在其中传递文件的字节数组而不是其位置:
Turns out that FileInputStream
would not find the path specified by resource
.
Luckily jsch
provides another method where you can pass the byte array of the file rather than its location:
jsch.addIdentity("coolfile.bin", toByteArray(ConfigurationClass.class.getResourceAsStream("/coolfile.bin")), null, null);
这篇关于Onejar和资源加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!