Example: Calling another Java program with java.lang.Runtime.exec()

This example shows how to call another Java™ program with java.lang.Runtime.exec(). This class calls the Hello program that is shipped as part of the IBM® Developer Kit for Java. When the Hello class writes to System.out, this program gets a handle to the stream and can read from it.

Source code for CallHelloPgm Java class

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
import java.io.*;
 
public class CallHelloPgm
{
   public static void main(String args[])
   {
      Process theProcess = null;
      BufferedReader inStream = null;
 
      System.out.println("CallHelloPgm.main() invoked");
 
      // call the Hello class
      try
      {
          theProcess = Runtime.getRuntime().exec("java QIBMHello");
      }
      catch(IOException e)
      {
         System.err.println("Error on exec() method");
         e.printStackTrace();  
      }
        
      // read from the called program's standard output stream
      try
      {
         inStream = new BufferedReader(
                                new InputStreamReader( theProcess.getInputStream() ));  
         System.out.println(inStream.readLine());
      }
      catch(IOException e)
      {
         System.err.println("Error on inStream.readLine()");
         e.printStackTrace();  
      }
   } 
}