Execute an external program read its output, and print its exit status : UNIX Win32 « Development Class « Java






Execute an external program read its output, and print its exit status

  

import java.io.*;

/**
 * ExecDemo shows how to execute an external program
 * read its output, and print its exit status.
 */
public class ExecDemoWait {

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

    // A Runtime object has methods for dealing with the OS
    Runtime r = Runtime.getRuntime();
    Process p;     // Process tracks one external native process
    BufferedReader is;  // reader for output of process
    String line;
    
    // Our argv[0] contains the program to run; remaining elements
    // of argv contain args for the target program. This is just
    // what is needed for the String[] form of exec.
    p = r.exec(argv);

    System.out.println("In Main after exec");

    // getInputStream gives an Input stream connected to
    // the process p's standard output. Just use it to make
    // a BufferedReader to readLine() what the program writes out.
    is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = is.readLine()) != null)
      System.out.println(line);
    
    System.out.println("In Main after EOF");
    System.out.flush();
    try {
      p.waitFor();  // wait for process to complete
    } catch (InterruptedException e) {
      System.err.println(e);  // "Can'tHappen"
      return;
    }
    System.err.println("Process done, exit status was " + p.exitValue());
    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.ExecDemo shows how to execute an external program
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