Skip to content

Instantly share code, notes, and snippets.

@mapiondev
Created June 29, 2010 10:22
Show Gist options
  • Save mapiondev/457049 to your computer and use it in GitHub Desktop.
Save mapiondev/457049 to your computer and use it in GitHub Desktop.
[java] 外部コマンド実行するクラス
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 StringBuilder stdout = new StringBuilder();
private StringBuilder stderr = new StringBuilder();
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;
StringBuilder output;
StreamReaderThread(final InputStream inputStream, StringBuilder 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, StringBuilder sb)
throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} finally {
reader.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment