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;
9 import java.nio.charset.Charset;
10 import java.nio.charset.IllegalCharsetNameException;
11 import java.nio.charset.UnsupportedCharsetException;
13 public class Command {
14 public static final String UTF_8 = "UTF-8";
15 private Charset m_charset;
17 public static class Result
19 private int m_retCode;
20 private String m_stdout;
21 private String m_stderr;
23 Result(int retCode, String stdout, String stderr) {
29 public int getRetCode() { return m_retCode; }
30 public String getStdout() { return m_stdout; }
31 public String getStderr() { return m_stderr; }
34 private class StreamGobbler extends Thread {
36 private StringBuilder m_sb;
37 private BufferedReader m_br;
39 public StreamGobbler(InputStream is) {
40 m_sb = new StringBuilder();
41 m_br = new BufferedReader(new InputStreamReader(is, m_charset));
48 line = m_br.readLine();
49 while (null != line) {
50 m_sb.append(line).append(System.lineSeparator());
51 line = m_br.readLine();
53 } catch (IOException exc) {
54 m_sb.append(Util.stringify(exc));
59 } catch (IOException exc) {
60 m_sb.append(Util.stringify(exc));
65 public String getOutput() { return m_sb.toString(); }
71 m_charset = Charset.forName(System.getProperty("file.encoding", UTF_8));
73 catch (IllegalCharsetNameException | UnsupportedCharsetException exc) {
74 m_charset = Charset.forName(UTF_8);
78 public Result exec(String cmd) throws IOException
84 Process proc = doRuntimeExec(cmd);
85 assert( null != proc );
87 StreamGobbler stdoutGobbler = new StreamGobbler(proc.getInputStream());
88 StreamGobbler stderrGobbler = new StreamGobbler(proc.getErrorStream());
90 stdoutGobbler.start();
91 stderrGobbler.start();
94 retCode = proc.waitFor();
98 stdout = stdoutGobbler.getOutput();
99 stderr = stdoutGobbler.getOutput();
101 } catch (InterruptedException exc) {
102 stderr += Util.stringify(exc);
105 return new Result(retCode, stdout, stderr);
108 Process doRuntimeExec(String cmd) throws IOException {
109 return Runtime.getRuntime().exec(cmd);