Home » Java Codes

Java Language Fundamentals – Execute external program with Runtime and Process classes

28 February 2009 128 views No Comment

To run an external program we need a reference to the Runtime which exists as a singleton within every Java runtime.
Executing the external program is done by calling the exec() method and it returns a reference to the process that has been created.
Now, in this case we run Notepad.exe and there won’t be any output from it written to the standard out, but in other cases there might be and it is possible to catch that information.
The Process class has a getInputStream() method that we can use to read the data, and we read for as long as the read() method doesn’t return -1.
The waitFor() method ensures that the Java program is not exited until the Process is finished. If the only goal is to start an external program then this line of code doesn’t make much sense, but if there were more Java code waiting to be executed that was dependent on the result of the process, then this method is very handy.

import java.io.DataInputStream;
import java.io.IOException;

/**
 *
 * @author javabout.com
 */

public class Main {
    
    /**
     * This method executes an external program (Notepad.exe)
     * and waits for it to finish before exiting.
     */

    public void executeExternalProgram() {
        try {
            
            //Get the reference to the Runtime instance
            Runtime runtime = Runtime.getRuntime();
            
            //Run the external program and receive a reference to the process
            Process proc = runtime.exec(“notepad.exe C:/test.txt”);
            
            //Read output data from the process while it has more
            DataInputStream bis = new DataInputStream(proc.getInputStream());
            
            int _byte;
            while ((_byte = bis.read()) != -1)
                System.out.print((char)_byte);
            
            
            //Wait for the process to finish
            proc.waitFor();
            
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().executeExternalProgram();
    }
}


Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave your response!

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>