ExecDemo shows how to execute an external program : UNIX Win32 « Development Class « Java






ExecDemo shows how to execute an external program

  
import java.io.*;

/**
 * ExecDemo shows how to execute an external program (in this case
 * the UNIX directory lister /bin/ls) and read its output.
 */
public class ExecDemoLs {
  /** The program to run */
  public static final String PROGRAM = "ls"; // "dir" for Windows
  /** Set to true to end the loop */
  static boolean done = false;

  public static void main(String argv[]) throws IOException {

    final Process p;     // Process tracks one external native process
    BufferedReader is;  // reader for output of process
    String line;
    
    p = Runtime.getRuntime().exec(PROGRAM);

    // 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 Thread() {
      public void run() {
        try {
          p.waitFor();
        } catch (InterruptedException ex) {
          // OK, just quit.
          return;
        }
        System.out.println("Program terminated!");
        done = 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 BufferedReader(new InputStreamReader(p.getInputStream()));

    while (!done && ((line = is.readLine()) != null))
      System.out.println(line);
    
    return;
  }
}



           
         
    
  








Related examples in the same category

1.Java 1.5 (5.0) Changes to the API: ProcessBuilder.
2.How to execute a program from within Java
3.How to execute an external program How to execute an external program
4.Show how to use exec to pass complex args
5.ExecDemo shows how to execute an external program 2
6.Execute an external program read its output, and print its exit status
7.Create some temp files, ls them, and rm them
8.ExecDemoHelp shows how to use the Win32 start command
9.ExecDemo shows how to execute an external program and read its output
10.ExecDemo shows how to execute an external program and read its output 3
11.UNIX getopt() system call
12.Unix Crypt
13.Handles program arguments like Unix getopt()
14.Helper method to execute shell command
15.dealing with Excel dates