Retrieving Command Line Output Using Java's Runtime.getRuntime()
To harness the power of command line utilities within Java, programmers often employ Runtime.getRuntime(). While this approach allows effortless execution of external programs, capturing their output can be perplexing. This article unravels the intricacies of retrieving command line output using Runtime.getRuntime().
To begin, consider this simplified example:
Runtime rt = Runtime.getRuntime(); String[] commands = {"system.exe", "-send", argument}; Process proc = rt.exec(commands);
By default, Runtime.getRuntime().exec() will return a Process object representing the executed program. However, the output generated by the program remains inaccessible through the Process object itself.
To retrieve the output, one needs to delve into the InputStreams associated with the Process object. There are two InputStreams to consider:
To read the standard output, employ a BufferedReader object:
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
Through stdInput, we can retrieve the output line by line using the readLine() method.
while ((s = stdInput.readLine()) != null) { System.out.println(s); }
To capture any errors, follow a similar approach with proc.getErrorStream().
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); while ((s = stdError.readLine()) != null) { System.out.println(s); }
By incorporating these streams into your code, you can effectively retrieve the output of command line programs executed via Runtime.getRuntime().
The above is the detailed content of How Can I Retrieve Command Line Output Using Java's Runtime.getRuntime()?. For more information, please follow other related articles on the PHP Chinese website!