O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required