Execute another jar in a java program

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

I had written several simple java applications named as A.jar, B.jar. Now i want to write a GUI java program so that user can press button A to execute A.jar and button B to execute B.jar .Also i want to output the runtime process detail in my GUI program. Any suggestion?

回答1:

If I understand correctly it appears you want to run the jars in a separate process from inside your java GUI application.

To do this you can use:

// 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();

Its always good practice to buffer the output of the process.



回答2:

.jar isn't executable. Instantiate classes or make call to any static method.

EDIT: Add Main-Class entry while creating a JAR.

>p.mf (content of 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");   } }

Use Process class and it's methods,

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


回答3:

Hope this helps:

public class JarExecutor {  private BufferedReader error; private BufferedReader op; private int exitVal;  public void executeJar(String jarFilePath, List args) throws JarExecutorException {     // Create run arguments for the      final List actualArgs = new ArrayList();     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 |         
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!