Get output of terminal command using Java

前端 未结 1 1140
遥遥无期
遥遥无期 2020-12-19 10:56

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

相关标签:
1条回答
  • 2020-12-19 11:46

    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

    0 讨论(0)
提交回复
热议问题