Home  >  Article  >  Java  >  How to Execute External Programs with Parameters in Java?

How to Execute External Programs with Parameters in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 16:25:30295browse

How to Execute External Programs with Parameters in Java?

Executing External Programs with Parameters

When attempting to invoke an external program from within a Java application, passing parameters can become a roadblock. Despite executing the program successfully, it may not perform its intended actions. This issue arises when attempting to pass parameters to the external program.

Solution:

To resolve this issue, consider the following code sample, which utilizes the ProcessBuilder class:

<code class="java">Process process = new ProcessBuilder("C:\PathToExe\MyExe.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 approach allows you to capture the output of the external program and handle it within your Java application. For additional information on passing commands, refer to the resources provided in the answer.

The above is the detailed content of How to Execute External Programs with Parameters 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