Java Reference
In-Depth Information
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
The original notion of standard output and standard error was that they would always be con-
nected to “the terminal”; this notion dates from an earlier time when almost all computer
users worked at the command line. Today, a program's standard and error output does not al-
ways 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:
public
public class
ExecDemoLs
{
/** The program to run */
public
class
ExecDemoLs
public static
final
String PROGRAM
=
"ls"
;
// "dir" for Windows
/** Set to true to end the loop */
static
static final
static volatile
volatile
boolean
boolean
done
=
false
false
;
public
public static
static
void
void
main
(
String argv
[])
throws
throws
IOException
{
final
final
Process p
;
// Process tracks one external native process
BufferedReader is
;
// reader for output of process
String line
;
p
=
Runtime
.
getRuntime
().
exec
(
PROGRAM
);
Debug
.
println
(
"exec"
,
"In Main after exec"
);
// Optional: start a thread to wait for the process to terminate.
// Don't just wait in main line, but here set a "done" flag and
// use that to control the main reading loop below.
Thread waiter
=
new
new
Thread
() {
public
public
void
void
run
() {