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 |