8

For some terminal commands, they repeatedly output. For example, for something that's generating a file, it may output the percent that it is complete.

I know how to call terminal commands in Java using

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

but that doesn't give me a live feed of the current output of the command. How can I do this so that I can do a System.out.println() every 100 milliseconds, for example, to see what the most recent output of the process was.

4

1 Answer 1

11

You need to read InputStream from the process, here is an example:

Edit I modified the code as suggested here to receive the errStream with the stdInput

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 purpose, you can read the input as bytes instead of using readLine just in case that the process does not terminate messages with newLine

Sign up to request clarification or add additional context in comments.

9 Comments

I tried this, but it seems to freeze at in.readLine() (it doesn't output anything, but doesn't end the while loop)
Maybe the command you're running doesn't output any \r or \n characters (which would signal the BufferedReader that it has read a complete line)? Maybe it doesn't generate any output in certain terminal modes (try piping the result to 'more' and see what it outputs)? Maybe the command writes its output to stderr instead of stdout?
It will freeze waiting for input, so either your processes does not terminate the data with newline or it does not write to the stdout at all
@dnault see the code I posted here for details of the Java code I tried: stackoverflow.com/questions/14915290/…
@CodeGuy Try exec'ing mencoder directly. Also, specify the command as a String[] instead of a single String (in case any of the arguments contain spaces).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.