How do I run another application from Java?
Author: Deron Eriksson
Description: This Java tutorial describes using Runtime's exec method to run another application from Java.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page:    1 2 >

In JavaSW, you can run another application by calling the exec method on the Runtime object, which may be obtained via a call to Runtime.getRuntime(). This tutorial will feature two examples, the first of which will open the Notepad application and close it after 5 seconds. The second example will run another Java process and read the output and error streams from that process. The project structure for this tutorial is shown below.

'testing' project

The first example features the RuntimeExecTest1 class. The Runtime object is obtained by calling Runtime.getRuntime(). Following this, the exec method is called on the runTime object, with "notepad" passed as a parameter. This call works because notepad is an executable that is present in the system path. If the directory containing notepad was not in the system path, this call (without the fully qualified path to notepad) would not work.

The call to exec opens a notepad window, and the 'process' object is obtained from the exec call. Following this, the call to Thread.sleep(5000) causes a pause in execution of RuntimeExecTest1 for 5 seconds. The destroy method is then called on 'process' which closes the notepad application.

RuntimeExecTest1.java

package test;

import java.io.IOException;

public class RuntimeExecTest1 {

	public static void main(String[] args) {
		try {
			System.out.println("Opening notepad");
			Runtime runTime = Runtime.getRuntime();
			Process process = runTime.exec("notepad");
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Closing notepad");
			process.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The execution of RuntimeExecTest1 is shown below. The screencapture is taken during the 5 second interval that the Notepad window was open. After 5 seconds, the process.destroy() call closes the notepad window.

Execution of RuntimeExecTest1

(Continued on page 2)

Page:    1 2 >