Execute external program with Runtime and Process classes
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 javadb.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(); } } |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Bookmark:
Search for code examples on this site
