【问题标题】:Run outer jar and this should execute inner jar运行外罐,这应该执行内罐
【发布时间】:2017-11-29 17:44:17
【问题描述】:

我在“outer.jar”文件中有一个主类。在这个 jar 中,classes/lib 文件夹中还有另一个名为“inner.jar”的 jar。当我使用命令java -jar outer.jar运行外罐时,如何使内罐运行?

我的主类正在运行另一个名为“inner.jar”的 jar 并使用输出。现在我的应用程序也被打包为一个名为“outer.jar”的jar,当我运行这个“outer.jar”时,主类无法运行inner.jar

外jar主类代码:

public class OuterJarMain{
    public static void main(String[] args) {

            String path = OuterJarMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            ProcessBuilder pb = new ProcessBuilder("java", "-jar", path.substring(1)+"lib/inner.jar", "1");
            try {
                Process p = pb.start();

            } catch (IOException e) {
                e.printStackTrace();
            }

当从 IDE 执行主类时,代码运行良好,因为 inner.jar 在 target/classes/lib 文件夹中可用。但是当我从命令行运行outer.jar时,路径显示为/C:/....../outer.jar!/.../classes!/,并且inner.jar没有被执行

【问题讨论】:

    标签: java jar executable-jar


    【解决方案1】:

    由于 jar 中的文件已存档,因此您无法像访问普通文件一样访问它们。

    你可以做的是将jar里面的条目复制到一个文件夹中,如this post所示,然后用java -jar执行jar,之后如果你不需要jar可以调用@987654323 @

    编辑:我修改了该帖子中的代码,示例如下所示。 该方法返回导出的inner jar的绝对位置。

    public static String exportInnerJar(){
        String jarDir = ""; 
        try {
            //Get the parent directory of the outer jar.
            jarDir = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("Fail to find the outer jar location");
            e.printStackTrace();
        }
        //The location of the inner jar
        //The example means the innar jar is at outer.jar/example/inner.jar where "example" is a folder under the root of the outer jar.
        InputStream is = ClassName.class.getResourceAsStream("/example/inner.jar");
    
        //The location to be exported to, you can change this to wherever you want
        File exportInnerJar = new File(jarDir).toPath().resolve("inner.jar").toFile();
    
        //Create the file
        exportInnerJar.createNewFile();
    
        //Use FileOutputStream to write to file
        FileOutputStream fos = new FileOutputStream(exportInnerJar);
    
        //setup a buffer
        int readBytes;
        byte[] buffer = new byte[4096];
    
        //export
        while ((readBytes = is.read(buffer)) > 0) {
            fos.write(buffer, 0, readBytes);
        }
    
        // close streams
        is.close();
        fos.close();
    
        return exportInnerJar.getAbsolutePath();
    }
    

    【讨论】:

    • 你好,我应该把内罐的主类导出到外罐的某个文件夹吗?我只想触发内部jar并使用outerjarmain.class中的process.getInputStream()使用输出
    • 你应该导出整个inner jar并执行它。
    • 这种方法是否适用于 linux、docker 等,因为我不知道要导出到的文件夹?
    • 可以选择导出的文件夹。我加了一个例子,你可以看看。
    • 嗨,我的主类在outer.jar里面。所以 jarDir 值不正确
    猜你喜欢
    • 1970-01-01
    • 2013-06-19
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2019-06-30
    相关资源
    最近更新 更多