Capturing stdout when calling Runtime.exec

Capturing stdout when calling Runtime.exec

When calling Runtime.exec() to run an external process in Java, you can capture its standard output (stdout) by reading the process's input stream. Here's how you can do it:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CaptureStdoutExample { public static void main(String[] args) { try { // Command to run an external process String command = "your-command-here"; // Start the external process Process process = Runtime.getRuntime().exec(command); // Create a BufferedReader to read the process's output BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; // Read and print the output line by line while ((line = reader.readLine()) != null) { System.out.println(line); } // Wait for the process to finish int exitCode = process.waitFor(); System.out.println("Process exited with code " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } 

In this example:

  1. You specify the external command you want to run in the command variable. Replace "your-command-here" with the actual command you want to execute.

  2. You use Runtime.getRuntime().exec(command) to start the external process.

  3. You create a BufferedReader to read the process's standard output stream using process.getInputStream().

  4. You loop through the output lines and print them one by one.

  5. You wait for the process to finish using process.waitFor(), which will block until the external process completes.

  6. Finally, you print the exit code of the process.

Make sure to handle exceptions such as IOException and InterruptedException that can occur during process execution and input/output operations.

This code captures and prints the standard output of the external process line by line as it's produced. You can modify it to save the output to a file or process it in any other way that suits your needs.


More Tags

angular2-http cursor-position android-popupwindow cron hint cloud9-ide raycasting report dialect timezone-offset

More Java Questions

More Trees & Forestry Calculators

More Other animals Calculators

More Investment Calculators

More Electronics Circuits Calculators