■
プロセスの実行させるにはRuntime.exec()を使いますが、コンソールアプリケーションで入出力がある場合は、それらのストリームのバッファ処理を実装する必要があります。
Antの中にプロセスを実行するタスクがあるのでそれが参考になります。
http://ant.apache.org/
上記のソースを参考にし、外部プロセスを実行するサンプルを作ってみました。実行には ant.jar が必要です。
import java.io.IOException;
import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import org.apache.tools.ant.taskdefs.StreamPumper;
public class ProcessTest {
/**
* 指定されたプロセスを実行する.
* プロセスは入力を伴わないものとする。
* 標準出力、標準エラー出力はSystem.out, System.errに出力される。
* @param command コマンド文字列(ex."java.exe -X")
* @return 戻り値。プロセスの実行に失敗した場合は、Integer.MAX_VALUE
を返す。
*/
int execute(String command) throws IOException {
Process process = Runtime.getRuntime().exec(command);
ExecuteStreamHandler streamHandler = new PumpStreamHandler();
try {
streamHandler.setProcessInputStream(process.getOutputStream());
streamHandler.setProcessOutputStream(process.getInputStream());
streamHandler.setProcessErrorStream(process.getErrorStream());
} catch (IOException e) {
process.destroy();
throw e;
}
streamHandler.start();
try {
int exitValue = Integer.MAX_VALUE;
try {
process.waitFor();
} catch (InterruptedException e) {
process.destroy();
}
exitValue = process.exitValue();
streamHandler.stop();
try { process.getInputStream().close(); } catch (IOException e) {}
try { process.getOutputStream().close(); } catch (IOException e) {}
try { process.getErrorStream().close(); } catch (IOException e) {}
return exitValue;
} catch (ThreadDeath t) {
process.destroy();
throw t;
}
}
public static void main(String[] args) throws Exception {
ProcessTest test = new ProcessTest();
int retcode = test.execute("java");
System.out.println("retcode="+retcode);
}
}
以前も似たソースを書いた覚えがあるのだけれど、どこにいったのかなぁ〜