The Java Runtime.getRuntime() allows for execution of command line programs from a Java program. Its exec() method takes an array of command arguments and returns a Process object. However, getting the output from the command is a different task altogether.
To retrieve command output, the Process object provides input and error streams through getInputStream() and getErrorStream(), respectively. Here's an enhanced version of your code that obtains and prints the output:
Runtime rt = Runtime.getRuntime(); String[] commands = {"system.exe", "-get t"}; Process proc = rt.exec(commands); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); // 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); }
By reading from the input stream, you can access and print the output from the command. Note that you may encounter errors during command execution, so it's advisable to also check the error stream using getErrorStream().
For more detailed information, refer to the Process API documentation. Alternatively, consider using the ProcessBuilder class for more control over process configuration.
The above is the detailed content of How Can I Capture and Display Command Output Using Java's Runtime.getRuntime()?. For more information, please follow other related articles on the PHP Chinese website!