Java Reference
In-Depth Information
for a Java program on a Windows system runs the MS-DOS batch file doDir.bat
that includes the line
dir *.java
to produce a directory listing. (A slightly different command is needed on a
Unix or Linux system. There are platform portable ways to get a directory listing
purely with Java code - see the java.io.File.list() method - but this
example serves to demonstrate how to call external programs.) The program
RuntTimeApp shown below launches doDir.bat and then reads the output
and prints it:
import java.io.*;
/** Demonstrates how to run an external program. **/
public class RunTimeApp
{
public static void main (String[] args) {
try {
Runtime rt = Runtime.getRuntime ();
// step 1
// Run the external program doDir.bat
Process process = rt.exec ("doDir.bat"); // step 2
InputStreamReader reader = // step 3
new InputStreamReader (process.getInputStream ());
BufferedReader buf - reader =
new BufferedReader (reader);
// step 4
String line;
while ((line = buf - reader.readLine ())!= null)
System.out.println (line);
}
catch (IOException e) {
System.out.println (e);
}
}
}
First an instance of the Runtime class is obtained with the factory method:
Runtime rt = Runtime.getRuntime ();
With the Runtime instance the program is run with the exec() method:
Process process = rt.exec ( " doDir.bat " );
 
Search WWH ::




Custom Search