When utilizing Java's Runtime.getRuntime() to execute command prompt commands from your program, you might encounter the difficulty of capturing the output the command returns. Let's delve into the problem and discover how to retrieve and print the desired output using a robust method.
In your approach, attempting to print the Process object proc using System.out.println() would not yield any meaningful results. Instead, you need to channel the InputStream from the executed command to a BufferedReader to access and subsequently print the output.
Here's an updated and fully functional code snippet:
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); }
By utilizing BufferedReader, you can iteratively read the output lines and display them in your program. This approach provides a clean and efficient way to handle both standard output and potential errors from the executed command.
Refer to the official Javadoc for Runtime.getRuntime() for comprehensive documentation and insights into additional options like ProcessBuilder, which offers advanced control over process handling.
The above is the detailed content of How Can I Capture and Print Output from Command Line Programs Using Java's Runtime.getRuntime()?. For more information, please follow other related articles on the PHP Chinese website!