Onejar and resource loading

2019-09-01 02:12发布

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条回答
贪生不怕死
2楼-- · 2019-09-01 02:40

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);
查看更多
登录 后发表回答