Java contains the functionality of initiating an external process - an executable file or an existing application on the system, such as Google Chrome or the Media Player- by simple Java code. One way is to use following two classes for the purpose:
Java
Runtime.getRuntime() simply returns the Runtime object 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 is not found. On running the code, an instance of Google Chrome opens up on the computer.
Another way to create an external process is using ProcessBuilder which has been discussed in below post.ProcessBuilder in Java to create a basic online Judge
- Process class
- Runtime class
// 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();
}
}
}