サンプル
例1 : バッチをJavaから実行する
実行バッチ:./etc/hello.bat (バッチ作成は、以下の関連記事を参照のこと)http://blogs.yahoo.co.jp/dk521123/16010990.html
http://blogs.yahoo.co.jp/dk521123/20448469.html
echo hello world! REM 第1引数をそのまま返す exit %1プログラム:Main.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { execute("./etc/hellow.bat", "0"); execute("./etc/hellow.bat", "1"); } private static void execute(String... commands) { ProcessBuilder processBuilder = new ProcessBuilder(commands); // 標準エラー出力を標準出力にマージする processBuilder.redirectErrorStream(true); 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); } } } catch (IOException | InterruptedException ex) { // 例外ハンドリング処理 } } }出力結果
Result Code : 0 hello world! Result Code : 1 hello world!
例2 : pg_dump を Javaから実行する
プログラム:Main.javaimport java.io.BufferedReader; import java.io.InputStreamReader; public class Main { private final static int Success = 0; public static void main(String[] args) { try { ProcessBuilder processBuilder = new ProcessBuilder( "C:/Program Files/PostgreSQL/9.3/bin/pg_dump.exe", "-Fc", "-b", "-U", "postgres", "-f", "C:/temp/dump.out", "postgres"); Process process = processBuilder.start(); int result = process.waitFor(); if (Success != result) { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( process.getErrorStream()))) { String errorResult; while ((errorResult = bufferedReader.readLine()) != null) { System.out.println(errorResult); } } catch (Exception ex) { ex.printStackTrace(); } } System.out.println("Done " + result); } catch (Exception ex) { ex.printStackTrace(); } } }