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!