Created
July 4, 2021 10:43
-
-
Save froop/77a02e1e1d0ea89e9ea60ff153a0b59d to your computer and use it in GitHub Desktop.
[Java] 外部プロセスの出力をスレッドを使用せずに吸い出す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 下記プログラムのスレッド非使用版。 | |
* 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