Running External Programs /Commands Using Java Runtime

Java Programming language allows the java application to access the operating system runtime and execute commands and get the results back. For instance, you can open a notepad application from the Java code. All you need to know is the location of the external application to run.

For example, if you want to start notepad, the application is located at C:/windows/system32/notepad.exe.

In this tutorial, I will show you how to run the external commands from within the java application.

I will be using windows ‘ping’ command located at C:/windows/system32/ping.exe and will ping the Sanjaal.com server.

Please note that every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

An application cannot create its own instance of this class, but instead can call the static getRunTime() method.

package com.kushal.runtime;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 *
 * This class invokes some external commands.
 * For demo, we are invoking the window's ping command.
 */
import java.io.*;

public class RunExternalCommands {

	public static void main(String argv[]) {
		try {
			String line;
			/**
			 * getRunTime() Returns the runtime object associated with the current
			 * Java application. Most of the methods of class Runtime are instance
			 * methods and must be invoked with respect to the current runtime object.
			 *
			 * exec() method Executes the specified string command in a separate
			 * process. The command argument is parsed into tokens and then
			 * executed as a command in a separate process. The token
			 * parsing is done by a java.util.StringTokenizer created by the call.
			 *
			 */
			Process p = Runtime.getRuntime().exec(
					"C:/windows/system32/ping.exe sanjaal.com");

			/**
			 * Create a buffered reader from the Process' input stream.
			 */
			BufferedReader input = new BufferedReader(new InputStreamReader(p
					.getInputStream()));

			/**
			 * Loop through the input stream to print the program output into console.
			 */
			while ((line = input.readLine()) != null) {
				System.out.println(line);
			}
			/**
			 * Finally close the reader
			 */
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

The ouput of running the above program:

Pinging sanjaal.com [66.96.133.22] with 32 bytes of data:
Reply from 66.96.133.22: bytes=32 time=48ms TTL=240
Reply from 66.96.133.22: bytes=32 time=47ms TTL=240
Reply from 66.96.133.22: bytes=32 time=45ms TTL=240
Reply from 66.96.133.22: bytes=32 time=47ms TTL=240

Ping statistics for 66.96.133.22:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 45ms, Maximum = 48ms, Average = 46ms

Running the same command manually from the windows command prompt:

About java.lang.Process object:
The Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.

There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object.