外部コマンドを実行(終了を待つ)

notepad.exeを引数つきで起動する例

package hoge;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class Run {
	private static String read(InputStream is) {
		StringBuilder sb = new StringBuilder();
		try {
			byte[] rBuf = new byte[20];
			boolean running = true;
			int cnt = 0;
			while (running) {
				if (is.available() < 1) {
					Thread.sleep(300);
					cnt++;
					if (10 == cnt) {
						running = false;
					}
					continue;
				}
				int len = is.read(rBuf);
				if (len < 1) {
					break;
				}
				sb.append(new String(rBuf));
			}
			System.out.println("");
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
			return "";
		}
		return sb.toString();
	}

	class ProcessDestroyer extends TimerTask {

		private Process process;

		public ProcessDestroyer(Process process) {
			this.process = process;
		}

		@Override
		public void run() {
			process.destroy(); // プロセスを強制終了
		}
	}

	public void execute() {
		List<String> params = new LinkedList<String>();
		params.add("cmd.exe");
		params.add("-c");
		params.add("dir");
		//params.add("notepad.exe");
		// params.add("test.txt");
		ProcessBuilder pb = new ProcessBuilder(params);
		try {
			Process p = pb.start();
			InputStream stdIn = p.getInputStream();
			InputStream errIn = p.getErrorStream();
			System.out.println("stdin:");
			System.out.println(Run.read(stdIn));
			stdIn.close();
			System.out.println("stderr:");
			System.out.println(Run.read(errIn));
			errIn.close();

			System.out.println("waitfor:");
			TimerTask task = new ProcessDestroyer(p);
			Timer timer = new Timer("プロセス停止タイマー");
			timer.schedule(task, TimeUnit.SECONDS.toMillis(3)); // 3秒後にProcessDestroyer#run()が呼ばれる

			while (true) {
				try {
					p.waitFor();
					break;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			timer.cancel(); // タイマーのキャンセル(必須)
			int ret = p.exitValue();
			System.out.println("process exited with value : " + ret);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Run run = new Run();
		run.execute();
	}
}

2014/8/15
最終更新:2014年08月15日 14:21