Home >Java >javaTutorial >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>
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>
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>
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!