Running a Program and Capturing Its Output


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


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


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

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. (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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.