为了账号安全,请及时绑定邮箱和手机立即绑定

在Java程序中执行另一个jar

在Java程序中执行另一个jar

大话西游666 2019-08-02 14:18:24
在Java程序中执行另一个jar我写了几个名为A.jar,B.jar的简单java应用程序。现在我想编写一个GUI java程序,以便用户可以按下按钮A执行A.jar,按钮B执行B.jar。此外,我想在我的GUI程序中输出运行时进程详细信息。有什么建议吗?
查看完整描述

3 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

如果我理解正确,您似乎希望在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();

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


查看完整回答
反对 回复 2019-08-02
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

希望这可以帮助:

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


查看完整回答
反对 回复 2019-08-02
  • 3 回答
  • 0 关注
  • 1621 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号