Home > Java > javaTutorial > body text

How to Execute an Executable and Pass Arguments in Java?

Linda Hamilton
Release: 2024-11-03 21:35:03
Original
802 people have browsed it

How to Execute an Executable and Pass Arguments in Java?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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