How to call an external program in java using process and runtime

Java includes the ability to start external processes through simple Java code-an executable file or an existing application on the system, such as Google Chrome or Media Player. One way is to use the following two classes:

  1. Process class
  2. Runtime class

The Process class in the java.lang package contains many useful methods, such as killing the child process, making the thread wait for a period of time, and returning to the I/O stream of the child process. Subsequently, the Runtime class provides an entry point Java runtime environment to interact with. It contains methods for executing processes, providing the number of available processors, displaying the available memory in the JVM, etc.

// A sample Java program (Written for Windows OS)
// to demonstrate creation of external process
// using Runtime and Process
class CoolStuff
{
	public static void main(String[] args)
	{
		try
		{
			// Command to create an external process
			String command = "C:\Program Files (x86)"+
				"\Google\Chrome\Application\chrome.exe";

			// Running the above command
			Runtime run = Runtime.getRuntime();
			Process proc = run.exec(command);
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}

Runtime.getRuntime() returns only Runtime objects associated with the current Java application. The executable path is specified in the process exec(String path) method. We also have an IOException try-catch block to handle the case where the file to be executed cannot be found. When you run the code, an instance of Google Chrome is opened on your computer.

Submit Your Programming Assignment Details