Home > Java > javaTutorial > body text

How to Execute an Executable and Pass Parameters from Java?

Linda Hamilton
Release: 2024-11-04 07:50:02
Original
229 people have browsed it

How to Execute an Executable and Pass Parameters from Java?

Call an Executable and Pass Parameters from Java

When working with external processes from Java, it's often necessary to call an executable and pass it specific parameters. This can be achieved through the ProcessBuilder class, as shown in the following code:

<code class="java">Process process = new ProcessBuilder("C:\PathToExe\MyExe.exe").start();

// Process output and error streams
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>
Copy after login

Passing Parameters

To pass parameters to the executable, simply provide them as arguments in the ProcessBuilder constructor:

<code class="java">Process process = new ProcessBuilder("C:\PathToExe\MyExe.exe", "param1", "param2").start();</code>
Copy after login

Handling Paths with Spaces

If the path to the executable contains spaces, you can enclose it in double quotes within the ProcessBuilder constructor:

<code class="java">Process process = new ProcessBuilder("\"C:\User\My applications\MyExe.exe\"").start();</code>
Copy after login

By following these modifications, you should be able to successfully call an executable and pass parameters from Java, even when spaces are present in the path to the executable.

The above is the detailed content of How to Execute an Executable and Pass Parameters from Java?. 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