Calling an Executable and Passing Parameters in Java
To call an executable file from Java and pass in arguments, utilize the following approach:
<code class="java">Process process = new ProcessBuilder("path/to/myexe.exe", "argument1", "argument2").start();</code>
This code creates a new process using the specified executable path and arguments. However, if your executable path contains spaces, you need to enclose it in double quotes:
<code class="java">Process process = new ProcessBuilder("\"path to myexe.exe\"", "argument1", "argument2").start();</code>
Once the process is started, you can access its input/output streams to retrieve the output of the executable:
<code class="java">InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.println("Output of running " + Arrays.toString(args) + ":"); while ((line = br.readLine()) != null) { System.out.println(line); }</code>
This code will print the output of the executable to the console. Note that you can also access the error stream (process.getErrorStream()) to capture any errors encountered by the executable.
The above is the detailed content of How to Execute an Executable and Pass Arguments in Java?. For more information, please follow other related articles on the PHP Chinese website!