"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I effectively execute external programs and retrieve their output in Java?

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

Published on 2024-11-15
Browse:780

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:

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);
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3