Java Reference
In-Depth Information
try
try
{
p
.
waitFor
();
}
catch
catch
(
InterruptedException ex
) {
// OK, just quit.
return
return
;
}
System
.
out
.
println
(
"Program terminated!"
);
done
=
true
true
;
}
};
waiter
.
start
();
// 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.
is
=
new
new
BufferedReader
(
new
new
InputStreamReader
(
p
.
getInputStream
()));
while
while
(!
done
&& ((
line
=
is
.
readLine
()) !=
null
null
))
System
.
out
.
println
(
line
);
Debug
.
println
(
"exec"
,
"In Main after EOF"
);
return
return
;
}
}
This is such a common occurrence that I've packaged it up into a class called
ExecAndPrint
,
which is part of my
com.darwinsys.lang
package.
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 24-3
shows the code for some of these methods.
Example 24-3. ExecAndPrint.java (partial listing)
/** Need a Runtime object for any of these methods */
protected
protected final
final static
static
Runtime r
=
Runtime
.
getRuntime
();
/** Run the command given as a String, printing its output to System.out */
public
public static
static
int
int
run
(
String cmd
)
throws
throws
IOException
{
return
return
run
(
cmd
,
new
new
OutputStreamWriter
(
System
.
out
));
}
/** Run the command given as a String, print its output to "out" */
public
public static
static
int
int
run
(
String cmd
,
Writer out
)
throws
throws
IOException
{