How to run a system application (executable) from Java

In many applications nowadays, it is necessary to rely on other applications during the runtime to guarantee the application integrity. For example, third party applications whose goal is to store a signature from a device installed on the computer. In Java this is pretty easy using the Runtime class, this class allows the application to interface with the environment in which the application is running. For example, in windows you will be able to open the Notepad.exe application using the alias notepad from the CLI, so with Java you should be able to start the notepad.exe application with the following 3 lines of code:

Runtime runTime = Runtime.getRuntime();
            
String executablePath = "notepad";

Process process = runTime.exec(executablePath);

However, you won't have always shortcuts for executables, so you will need to provide the absolute path to the executable. In this short article, we'll provide you with a short snippet that allows you to start a third party application from the system easily.

Full example

The following snippet packed within an application, will start the application (executable) defined in the executablePath variable and will catch any exception triggered by the example:

package sandbox;

import java.io.IOException;

public class Sandbox {
    
    /**
     * Example of how to run an executable from Java.
     * 
     * @param args 
     */
    public static void main(String[] args) {
        try {
            Runtime runTime = Runtime.getRuntime();
            
            String executablePath = "C:\\Users\\sdkca\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe";
            
            Process process = runTime.exec(executablePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If the executable doesn't exist, the code will catch the exception and will display in the console an output similar to:

java.io.IOException: Cannot run program "my-executable-path.exe": CreateProcess error=2, The system cannot find the file specified
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
	at java.lang.Runtime.exec(Runtime.java:620)
	at java.lang.Runtime.exec(Runtime.java:450)
	at java.lang.Runtime.exec(Runtime.java:347)
	at sandbox.Sandbox.main(Sandbox.java:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
	at java.lang.ProcessImpl.create(Native Method)
	at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
	at java.lang.ProcessImpl.start(ProcessImpl.java:137)
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)

Happy coding !

This could interest you

Become a more social person