Simplest way to get command output in java

221 Views Asked by At

I know you can use use following to run a command for linux in java and get the output from the command you just ran.

Process p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();
StringBuffer sb = new StringBuffer();
BufferedReader reader = 
     new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";           
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
}

I am however wondering, is there any simpler way of getting the output from the command that was ran?

1

There are 1 best solutions below

0
On BEST ANSWER

This is the code I use. It

  • combines errors and output so if you get an error you still see it.
  • reads the data as it is produced so the buffer doesn't fill up.
  • doesn't remove new line only to add them back in.

.

private static String run(String... cmds) throws IOException {
    ProcessBuilder pb = new ProcessBuilder(cmds);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    StringWriter sw = new StringWriter();
    char[] chars = new char[1024];
    try (Reader r = new InputStreamReader(process.getInputStream())) {
        for (int len; (len = r.read(chars)) > 0; ) {
            sw.write(chars, 0, len);
        }
    }
    return sw.toString();
}