Java Runtime.getRuntime(): Extracting Output from Executed Command Line Programs
Issue:
When executing command line programs using Runtime.getRuntime(), the output returned by the commands is not readily available to the Java program. This issue arises when attempting to retrieve a specific output, which requires further processing of the returned values.
Solution:
To obtain the output from an executed command, the following steps are necessary:
Additional Considerations:
Sample Code:
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 output and errors System.out.println("Standard Output:"); String line; while ((line = stdInput.readLine()) != null) { System.out.println(line); } System.out.println("Standard Error:"); while ((line = stdError.readLine()) != null) { System.out.println(line); }
By following these steps and implementing the provided code示例, you can effectively retrieve the output of executed command line programs and utilize it within your Java application.
The above is the detailed content of How to Capture Command Line Output Using Java's Runtime.getRuntime()?. For more information, please follow other related articles on the PHP Chinese website!