Java Runtime.getRuntime(): getting output from executing a command line program

前端 未结 12 1652
清歌不尽
清歌不尽 2020-11-22 00:18

I\'m using the runtime to run command prompt commands from my Java program. However, I\'m not aware of how I can get the output the command returns.

Here is my code:

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 00:48

    Try reading the InputStream of the runtime:

    Runtime rt = Runtime.getRuntime();
    String[] commands = {"system.exe", "-send", argument};
    Process proc = rt.exec(commands);
    BufferedReader br = new BufferedReader(
        new InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = br.readLine()) != null)
        System.out.println(line);
    

    You might also need to read the error stream (proc.getErrorStream()) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder.

提交回复
热议问题