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

前端 未结 12 1376
清歌不尽
清歌不尽 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:49

    Also we can use streams for obtain command output:

    public static void main(String[] args) throws IOException {
    
            Runtime runtime = Runtime.getRuntime();
            String[] commands  = {"free", "-h"};
            Process process = runtime.exec(commands);
    
            BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            lineReader.lines().forEach(System.out::println);
    
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            errorReader.lines().forEach(System.out::println);
        }
    

提交回复
热议问题