简体   繁体   English

导出时从另一个Jar运行一个Jar不起作用

[英]Running a Jar from another Jar doesn't work when exported

I've been reading about the subject for a few hours: 我已经阅读了几个小时的主题:

What I'd like to do (and succeeded to do) is to run a runnable jar from my code, the thing is, when I export the code into a runnable jar, then it stops working. 我想做(并成功做)的是从我的代码运行一个可运行的jar,问题是,当我将代码导出到一个可运行的jar中时,它停止了工作。

The method that works from my compiler is : 从我的编译器工作的方法是:

ProcessBuilder pb = new ProcessBuilder("java", "-jar", "JAR I'M LOADING");
pb.start

This is what I've tried : 这是我尝试过的:

I've created a packet with the jar that I wanna run, and I created a static JarLoader class where I do : 我已经创建了一个要运行的jar包,并在其中创建了一个静态JarLoader类:

public class JarLoader {

    static JarLoader jl = new JarLoader();

    public static ProcessBuilder loadJar(){
        return new  ProcessBuilder("java", "-jar", jl.getClass().getResource("JAR I'M TRYING TO LOAD").toString());

}

And of course I switched the method that is runs the jar to : 当然,我将运行jar的方法切换为:

ProcessBuilder pb = JarLoader.loadJar();
pb.start();

This technique worked very well with other type of resources, such as images, but it doesn't work with the jar. 该技术在其他类型的资源(例如图像)上效果很好,但是在jar中却无法使用。

Am I missing something ? 我想念什么吗? (and yes, I did add the folder containing the Jar and the JarLoader to the project's source) (是的,我确实将包含Jar和JarLoader的文件夹添加到项目的源代码中)

The technique you're currently using allows you to get to a resource that's already packed inside your JAR file. 当前使用的技术允许您访问JAR文件中已经打包的资源。 But these resources are coherent only within the application, and not from outside it. 但是这些资源仅在应用程序内部是一致的,而不是在应用程序外部。

When you execute your JAR file using java -jar ... , that's an external application being executed, and it won't understand how to retrieve a JAR from inside another JAR. 当您使用java -jar ...执行JAR文件时,这是一个正在执行的外部应用程序,它将无法理解如何从另一个JAR内部检索JAR。 You will need to write it temporarily to disk, and then run the temporary JAR file. 您将需要将其临时写入磁盘,然后运行临时JAR文件。

You need to: 你需要:

  1. Open the resource as a stream. 作为流打开资源。
  2. Use Files.createTempFile() to create a temporary JAR file somewhere. 使用Files.createTempFile()在某个地方创建一个临时JAR文件。
  3. Use Files.copy() to copy from the resource stream to the temporary file. 使用Files.copy()从资源流复制到临时文件。
  4. Use File.deleteOnExit() to make sure that the temporary file will get cleaned up when the main (host) application terminates. 使用File.deleteOnExit()确保当主(主机)应用程序终止时临时文件将被清理。
  5. Execute the temporary file with java -jar tempfile.jar or whatever you called it. 使用java -jar tempfile.jar或您所谓的临时文件执行该临时文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM