Home > Java > javaTutorial > How Can I Retrieve Command Line Output Using Java's Runtime.getRuntime()?

How Can I Retrieve Command Line Output Using Java's Runtime.getRuntime()?

Patricia Arquette
Release: 2024-12-31 10:10:14
Original
275 people have browsed it

How Can I Retrieve Command Line Output Using Java's Runtime.getRuntime()?

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);
Copy after login

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:

  • proc.getInputStream(): This stream provides access to the standard output of the executed program.
  • proc.getErrorStream(): This stream captures any error messages or warnings generated by the program.

To read the standard output, employ a BufferedReader object:

BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
Copy after login

Through stdInput, we can retrieve the output line by line using the readLine() method.

while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template