Skip to content

Instantly share code, notes, and snippets.

@haruo31
Forked from mapiondev/ProcessBroker.java
Last active April 20, 2018 10:44
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 haruo31/261273507f54fe7d89eecb0bd082156b to your computer and use it in GitHub Desktop.
Save haruo31/261273507f54fe7d89eecb0bd082156b to your computer and use it in GitHub Desktop.
[java] 外部コマンド実行するクラス(スレッド安全版?)
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* ProcessBroker pb = new ProcessBroker("ps -ef | grep java".split(" "));
* pb.execute();
* System.out.println(pb.getStdout());
* System.out.println(pb.getStderr());
*/
public class ProcessBroker {
private List<String> command = new ArrayList<String>();
private StringBuffer stdout = new StringBuffer();
private StringBuffer stderr = new StringBuffer();
public ProcessBroker(String... command) {
this.command.addAll(Arrays.asList(command));
}
public int execute() throws IOException, InterruptedException {
Process process = new ProcessBuilder(command).start();
new StreamReaderThread(process.getInputStream(), stdout).start();
new StreamReaderThread(process.getErrorStream(), stderr).start();
return process.waitFor();
}
public String getStdout() {
return stdout.toString();
}
public String getStderr() {
return stderr.toString();
}
class StreamReaderThread extends Thread {
InputStream inputStream;
StringBuffer output;
StreamReaderThread(final InputStream inputStream, StringBuffer output) {
this.inputStream = inputStream;
this.output = output;
}
@Override
public void start() {
try {
readStream(inputStream, output);
} catch (IOException e) {
output.append(e.getMessage());
}
}
private void readStream(InputStream inputStream, StringBuffer sb)
throws IOException {
try (Reader reader = new InputStreamReader(inputStream)) {
char[] buf = new char[1 << 20]; // 1MiB buffer
int n;
while ((n = reader.read(buf, 0, buf.length)) > -1) {
sb.append(buf, 0, n);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment