Get output of a terminal command using Java

For some terminal commands, they output multiple times. For example, for something that generates a file, it might output the percentages that it fills in.

I know how to invoke terminal commands in Java using

Process p = Runtime.getRuntim().exec("command goes here");

      

but that doesn't give me a live stream of the current command output. How can I do this so that I can do it System.out.println()

every 100 milliseconds, for example, to find out what the last result of the process was.

+3


source to share


1 answer


You need to read InputStream

from the process, here is an example:

Edit . I changed the code here to get errStream

withstdInput



ProcessBuilder builder = new ProcessBuilder("command goes here");
builder.redirectErrorStream(true);
Process process = builder.start();
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String line = null;
while ((line = reader.readLine()) != null) {
   System.out.println(line);
}

      

For debugging purposes, you can read input as bytes instead of using readLine

only if the process does not terminate messages withnewLine

+1


source







All Articles