Home > Java > javaTutorial > body text

How can I effectively execute external programs and retrieve their output in Java?

Patricia Arquette
Release: 2024-10-31 04:28:30
Original
482 people have browsed it

How can I effectively execute external programs and retrieve their output in Java?

Executing External Programs in Java

In your Java program, you're attempting to execute an external program ("program.exe") using the Runtime.exec() method. While it doesn't produce errors, the program appears to be ineffective.

The provided code utilizes the Runtime.exec(params) method to initiate the external program. However, this method has limitations in handling input and output data between the Java program and the external process.

To effectively interact with an external program and retrieve its output, you can utilize the ProcessBuilder class. Here's an example that demonstrates how to execute the "program.exe" program with specific parameters:

<code class="java">ProcessBuilder processBuilder = new ProcessBuilder("C:\Users\user\Desktop\program.exe",
        "C:\Users\user\Desktop\images.jpg", "C:\Users\user\Desktop\images2.txt");
Process process = processBuilder.start();

InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;
System.out.println("Output of running program.exe with parameters:");

while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line);
}</code>
Copy after login

In this code, we create a ProcessBuilder instance with the required parameters. The start() method is used to initiate the external program. We then use an InputStream to read the program's output, convert it to characters using an InputStreamReader, and finally store it in a BufferedReader for easier line-by-line processing.

The above is the detailed content of How can I effectively execute external programs and retrieve their output 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