Home >Java >javaTutorial >How to Efficiently Capture Command Line Output in Java?
Extracting Command Line Output in Java
Java's Runtime class provides the ability to execute command line programs. However, obtaining the output generated by these commands can be a challenging task. This article addresses this issue by explaining how to extract the output from a command line program using the Runtime class.
In the provided code, the error message reveals that the output stream is not being read properly. To rectify this, the following code demonstrates a robust method:
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); }
This code utilizes the Runtime class to execute the command and opens readers for both the standard input and error streams of the process. It then iterates over the lines of output and errors, printing them to the console.
For more comprehensive details and advanced options, consult the Java documentation on ProcessBuilder: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
The above is the detailed content of How to Efficiently Capture Command Line Output in Java?. For more information, please follow other related articles on the PHP Chinese website!