Home  >  Article  >  Java  >  How to Execute External Programs and Read Their Output in Java?

How to Execute External Programs and Read Their Output in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 15:37:02129browse

How to Execute External Programs and Read Their Output in Java?

Executing External Programs Effectively

When attempting to execute an external program from a Java application, it's crucial to ensure that the program operates correctly and responds appropriately. In your case, you aimed to execute the "program.exe" executable and pass two parameters to it. While your code lacks any error notifications, it's evident that the program hasn't performed the intended actions.

The provided solution leverages the functionality of "ProcessBuilder" to initiate the execution of an external program. This class allows you to specify the complete command and its parameters, and includes support for reading the output generated by the executed program.

The optimized code:

<code class="java">Process process = new ProcessBuilder("C:\PathToExe\program.exe", "param1", "param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}</code>

This revised code ensures that the external program is executed by invoking the "start()" method of "ProcessBuilder." It then proceeds to gather and display any output produced by the executed program through the use of "getInputStream," "InputStreamReader," and "BufferedReader."

The above is the detailed content of How to Execute External Programs and Read Their Output in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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