Onejar and resource loading

自古美人都是妖i 提交于 2019-12-12 04:17:42

问题


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>

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);

When I run Application.java from the IDE (eclipse), the entire application loads successfully.

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

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?


回答1:


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);


来源:https://stackoverflow.com/questions/23276836/onejar-and-resource-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!