0

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?

7
  • I suggest you read the data as it is produced. If your buffer fills up, your program will stop waiting for your reader, however you don't read until the program finishes. Commented Jun 26, 2015 at 13:22
  • ProcessBuilder has some simpler ways of dealing with IO. Also the way you have coded this has potential to block execution or loose output. You should use a thread to read the output and you should set that thread up prior to the waitfor call. Commented Jun 26, 2015 at 13:24
  • @PeterLawrey so take out the Process.waitFor() call, correct? Commented Jun 26, 2015 at 13:24
  • @jgr208 or move it to the end if you want the exit code. BTW I wouldn't use StringBuffer as it was replaced ten years about by StringBuilder and wouldn't read the output line by line this way. Commented Jun 26, 2015 at 13:26
  • @PeterLawrey yea, this was just some example code I grabbed. But at least glad I am getting these suggestions before I put the example code into actual use. Commented Jun 26, 2015 at 13:27

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.