在Java程序中执行另一个jar

问题描述 投票:101回答:6

我写了几个名为A.jar,B.jar的简单java应用程序。

现在我想编写一个GUI java程序,以便用户可以按下按钮A执行A.jar,按钮B执行B.jar。

此外,我想在我的GUI程序中输出运行时进程详细信息。

有什么建议吗?

java jar executable-jar
6个回答
58
投票

如果我理解正确,您似乎希望在java GUI应用程序内部的单独进程中运行jar。

为此,您可以使用:

// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

缓冲过程输出总是很好的做法。


22
投票

.jar不可执行。实例化类或调用任何静态方法。

编辑:创建JAR时添加Main-Class条目。

> p.mf(p.mf的含量)

Main-Class:pk.Test

>Test.java

package pk;
public class Test{
  public static void main(String []args){
    System.out.println("Hello from Test");
  }
}

使用Process类及其方法,

public class Exec
{
   public static void main(String []args) throws Exception
    {
        Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
        ps.waitFor();
        java.io.InputStream is=ps.getInputStream();
        byte b[]=new byte[is.available()];
        is.read(b,0,b.length);
        System.out.println(new String(b));
    }
}

12
投票

希望这可以帮助:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

0
投票

如果jar在你的类路径中,并且你知道它的Main类,你可以只调用主类。以DITA-OT为例:

import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')

请注意,这将使下级jar共享内存空间和jar的类路径,并且可能导致干扰。如果您不希望污染的东西,您还有其他选择,如上所述 - 即:

  • 用jar创建一个新的ClassLoader。这更安全;如果你用你将使用外星罐子的知识来构建东西,你至少可以将新jar的知识隔离到核心类加载器。这就是我们在我的插件系统中所做的事情;主应用程序是一个带有ClassLoader工厂的小外壳,API的副本,以及真正的应用程序是第一个应该构建ClassLoader的插件的知识。插件是一对罐子 - 接口和实现 - 被压缩在一起。 ClassLoader都共享所有接口,而每个ClassLoader只知道自己的实现。堆栈有点复杂,但它通过所有测试并且工作得很漂亮。
  • 使用Runtime.getRuntime.exec(...)(完全隔离jar,但具有正常的“找到应用程序”,“正确地逃避你的字符串”,“特定于平台的WTF”和“OMG系统线程”运行系统命令的缺陷。

0
投票

以下工作原理通过使用批处理文件启动jar,以防程序作为独立运行:

public static void startExtJarProgram(){
        String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
        ProcessBuilder processBuilder = new ProcessBuilder(extJar);
        processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
        processBuilder.redirectInput();
        try {
           final Process process = processBuilder.start();
            try {
                final int exitStatus = process.waitFor();
                if(exitStatus==0){
                    System.out.println("External Jar Started Successfully.");
                    System.exit(0); //or whatever suits 
                }else{
                    System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                    System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
                    System.exit(1);//whatever
                }
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException: "+ex.getMessage());
            }
        } catch (IOException ex) {
            System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
        }
        System.out.println("Process Terminated.");
        System.exit(0);
    }

在批处理file.bat中,我们可以说:

@echo off
start /min C:\path\to\jarprogram.jar

-2
投票

如果您是java 1.6,那么还可以执行以下操作:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.