Skip to content

Instantly share code, notes, and snippets.

@kiwanami
Last active August 29, 2015 14:18
Show Gist options
  • Save kiwanami/47520d474be1a6645992 to your computer and use it in GitHub Desktop.
Save kiwanami/47520d474be1a6645992 to your computer and use it in GitHub Desktop.
Process.execにて、スレッド使わずに外部コマンド実行する
import java.io.*;
public class ProcessRun {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("locate javac");
InputStream stdout = p.getInputStream();
InputStream stderr = p.getErrorStream();
int val = 0;
while (true) {
String so = readString(stdout);
if (so != null) System.out.println(so);
String se = readString(stderr);
if (se != null) System.err.println(se);
if (so != null || se != null) continue;
// 両方空だったら、終了かも知れない
try {
val = p.exitValue();
break;
} catch (IllegalThreadStateException e) {
// do nothing
}
Thread.sleep(50);
}
p.destroy();
System.out.println("Exit: "+val);
}
private static byte[] buf = new byte[1024];
private static String readString(InputStream in) throws IOException {
int num = in.available();
if (num > 0) {
if (num > buf.length) buf = new byte[num];
int ret = in.read(buf,0,Math.min(num, buf.length));
if (ret < 0) return null;
return new String(buf,0,ret);
// ※厳密な文字コード変換は省略。
// OutputStreamWriterとか使ってバイナリの切れ目をJavaに判断させる
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment