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

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

    Here is the way to go:

    Runtime rt = Runtime.getRuntime();
    String[] commands = {"system.exe", "-get t"};
    Process proc = rt.exec(commands);
    
    BufferedReader stdInput = new BufferedReader(new 
         InputStreamReader(proc.getInputStream()));
    
    BufferedReader stdError = new BufferedReader(new 
         InputStreamReader(proc.getErrorStream()));
    
    // Read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    
    // Read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    

    Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

提交回复
热议问题