1 package net.jaekl.cfb.util;
3 // Copyright (C) 2015 Christian Jaekl
5 import java.io.BufferedReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
10 public class Command {
11 public static class Result
13 private int m_retCode;
14 private String m_stdout;
15 private String m_stderr;
17 Result(int retCode, String stdout, String stderr) {
23 public int getRetCode() { return m_retCode; }
24 public String getStdout() { return m_stdout; }
25 public String getStderr() { return m_stderr; }
28 private static class StreamGobbler extends Thread {
30 private StringBuilder m_sb;
31 private BufferedReader m_br;
33 public StreamGobbler(InputStream is) {
34 m_sb = new StringBuilder();
35 m_br = new BufferedReader(new InputStreamReader(is));
42 line = m_br.readLine();
43 while (null != line) {
44 m_sb.append(line).append(System.lineSeparator());
45 line = m_br.readLine();
47 } catch (IOException exc) {
48 m_sb.append(Util.stringify(exc));
53 } catch (IOException exc) {
54 m_sb.append(Util.stringify(exc));
59 public String getOutput() { return m_sb.toString(); }
67 public Result exec(String cmd) throws IOException
73 Process proc = doRuntimeExec(cmd);
74 assert( null != proc );
76 StreamGobbler stdoutGobbler = new StreamGobbler(proc.getInputStream());
77 StreamGobbler stderrGobbler = new StreamGobbler(proc.getErrorStream());
79 stdoutGobbler.start();
80 stderrGobbler.start();
83 retCode = proc.waitFor();
87 stdout = stdoutGobbler.getOutput();
88 stderr = stdoutGobbler.getOutput();
90 } catch (InterruptedException exc) {
91 stderr += Util.stringify(exc);
94 return new Result(retCode, stdout, stderr);
97 Process doRuntimeExec(String cmd) throws IOException {
98 return Runtime.getRuntime().exec(cmd);