Running a Program and Capturing Its Output
You want to run a program but also capture its output.
; 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 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
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
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 ...