サンプル
OtherJava.java
別プロセスとして実行したいJava。 OtherJava.jar にするpublic class OtherJava { public static void main(String[] args) throws Exception { if (args == null || args.length < 1) { throw new IllegalArgumentException("Illegal Arguments"); } String input = args[0]; if (input.equals("error")) { System.err.println("error..."); throw new Exception("error"); } else if (input.equals("return_code_10")) { System.out.println("Return Code 10..."); System.exit(10); } System.out.println("Hello World, " + input); } }
Main.java
呼び出し側import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Test0"); execute("java", "-jar", "OtherJava.jar"); Thread.sleep(1000L); System.out.println(); System.out.println("Test1"); execute("java", "-jar", "OtherJava.jar", "error"); Thread.sleep(1000L); System.out.println(); System.out.println("Test2"); execute("java", "-jar", "OtherJava.jar", "return_code_10"); Thread.sleep(1000L); System.out.println(); System.out.println("Test3"); execute("java", "-jar", "OtherJava.jar", "Mike"); Thread.sleep(1000L); System.out.println(); System.out.println("Done"); } private static void execute(String... commands) { ProcessBuilder processBuilder = new ProcessBuilder(commands); try { Process process = processBuilder.start(); int result = process.waitFor(); System.out.println("Result Code : " + result); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } try (BufferedReader errorBufferedreader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { String errorLine; while ((errorLine = errorBufferedreader.readLine()) != null) { System.err.println(errorLine); } } } catch (Exception ex) { ex.printStackTrace(); } } }
出力結果
Test0 Result Code : 1 Exception in thread "main" java.lang.IllegalArgumentException: Illegal Arguments at com.sample.proc.OtherJava.main(OtherJava.java:6) Test1 Result Code : 1 error... Exception in thread "main" java.lang.Exception: error at com.sample.proc.OtherJava.main(OtherJava.java:12) Test2 Result Code : 10 Return Code 10... Test3 Result Code : 0 Hello World, Mike Done
参考文献
https://stackoverflow.com/questions/1320476/execute-another-jar-in-a-java-program独自のリターンコードを設定するのに参考にした
http://takuan93.blog62.fc2.com/blog-entry-10.html