Skip to content

Instantly share code, notes, and snippets.

@froop
Created July 4, 2021 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save froop/77a02e1e1d0ea89e9ea60ff153a0b59d to your computer and use it in GitHub Desktop.
Save froop/77a02e1e1d0ea89e9ea60ff153a0b59d to your computer and use it in GitHub Desktop.
[Java] 外部プロセスの出力をスレッドを使用せずに吸い出す
/*
* 下記プログラムのスレッド非使用版。
* https://gist.github.com/froop/b09dd1b687599e0cb1031f3fb6ce0fe2
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
class StreamPoller {
InputStream is;
PrintStream os;
boolean terminated;
StreamPoller(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void poll() throws IOException {
if (this.terminated) {
return;
}
StringBuilder buf = new StringBuilder();
while (is.available() > 0) {
char c;
if ((c = (char) is.read()) == -1) {
os.print(buf.toString());
this.terminated = true;
return;
}
buf.append(c);
if (c == '\n') {
os.print(buf.toString());
buf = new StringBuilder();
}
}
}
}
public class CommandExecNoThread {
private static final int POLLING_INTERVAL = 100; // millisec
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec(args[0]);
StreamPoller errPoller = new StreamPoller(proc.getErrorStream(), System.err);
StreamPoller outPoller = new StreamPoller(proc.getInputStream(), System.out);
while (proc.isAlive()) {
errPoller.poll();
outPoller.poll();
Thread.sleep(POLLING_INTERVAL);
}
errPoller.poll();
outPoller.poll();
System.exit(proc.exitValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment