在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();
缓冲过程输出总是很好的做法。

杨__羊羊
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;}}
添加回答
举报
0/150
提交
取消