Get output of terminal command using Java

廉价感情. 提交于 2019-12-19 03:22:48

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/14915319/get-output-of-terminal-command-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!