Running a Program and Capturing Its Output

Problem

You want to run a program but also capture its output.

Solution

Use the Process object’s getInputStream( ) ; read and copy the contents to System.out or wherever you want them.

Discussion

A program’s standard and error output does not automatically appear anywhere. Arguably, there should be an automatic way to make this happen. But for now, you need to add a few lines of code to grab the program’s output and print it:

// part of ExecDemoLs.java        
p = Runtime.getRuntime(  ).exec(PROGRAM);
 
// getInputStream gives an Input stream connected to
// the process p's standard output (and vice versa). We use
// that to construct a BufferedReader so we can readLine(  ) it.
BufferedReader is = 
    new BufferedReader(new InputStreamReader(p.getInputStream(  )));
 
while ((line = is.readLine(  )) != null)
    System.out.println(line);

This is such a common occurrence that I’ve packaged it up into a class called ExecAndPrint, part of my package com.darwinsys.util . ExecAndPrint has several overloaded forms of its run( ) method (see the documentation for details), but they all take at least a command, and optionally an output file to which the command’s output is written. Example 26-2 shows the code for some of these methods.

Example 26-2. ExecAndPrint.java (partial listing)

/** Need a Runtime object for any of these methods */ protected static Runtime r = Runtime.getRuntime( ); /** Run the command given as a String, printing its output to System.out */ public static ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.