Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get output of terminal command using Java

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.

like image 256
CodeGuy Avatar asked Feb 16 '13 21:02

CodeGuy


People also ask

How do I run a terminal command in Java?

ProcessBuilder: Executing Command from Strings command("cmd", "/c", "dir C:\\Users"); Process process = processBuilder. start(); printResults(process); To actually execute a Process , we run the start() command and assign the returned value to a Process instance.

How do I run an openssl command in Java?

Runtime runtime = Runtime. getRuntime(); runtime. exec("openssl pkcs8 -inform der -nocrypt test.

What is runtime getRuntime () exec?

In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.


1 Answers

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

like image 127
iTech Avatar answered Sep 28 '22 21:09

iTech