Java Reference
In-Depth Information
Process p
=
r
.
exec
(
cmd
);
FileIO
.
copyFile
(
new
new
InputStreamReader
(
p
.
getInputStream
()),
out
,
true
true
);
try
try
{
p
.
waitFor
();
// wait for process to complete
}
catch
catch
(
InterruptedException e
) {
return
return
-
1
;
}
return
return
p
.
exitValue
();
}
As a simple example of using
exec()
directly along with
ExecAndPrint
, I'll create three
temporary files, list them (directory listing), and then delete them. When I run the
ExecDe-
moFiles
program, it lists the three files it has created:
-rw------- 1 ian wheel 0 Jan 29 14:29 file1
-rw------- 1 ian wheel 0 Jan 29 14:29 file2
-rw------- 1 ian wheel 0 Jan 29 14:29 file3
Its source code is in
Example 24-4
.
Example 24-4. ExecDemoFiles.java
// Get and save the Runtime object.
Runtime rt
=
Runtime
.
getRuntime
();
// Create three temporary files (the slow way!)
rt
.
exec
(
"mktemp file1"
);
rt
.
exec
(
"mktemp file2"
);
rt
.
exec
(
"mktemp file3"
);
// Run the "ls" (directory lister) program
// with its output sent into a file
String
[]
args
= {
"ls"
,
"-l"
,
"file1"
,
"file2"
,
"file3"
};
ExecAndPrint
.
run
(
args
);
rt
.
exec
(
"rm file1 file2 file3"
);
A process isn't necessarily destroyed when the Java program that created it exits or bombs
out. Simple text-based programs will be, but window-based programs like
kwrite
, Netscape,
or even a Java-based
JFrame
application will not. For example, our
ExecDemoNS
program
started Netscape, and when
ExecDemoNS
's Exit button is clicked,
ExecDemoNS
exits but Nets-
cape stays running. What if you want to be sure a process has completed? The
Process
ob-