JAVA: Lunch an external program

In order to launch external program through java we have to use one of the overloaded exec() method present in the java.lang.Runtime class or set up a Process builder and call its start() method. Here in a simple way we will use the exec() method available in the Runtime class which enables us to run an external program very easily.

The command or program name is usually broken into strings by a simple StringTokenizer or in the form of string literal in case of single string word and passed on to the operating system’s “execute a program” system call internally by running JVM instance when below program executes.

Please find below example program that uses exec() method to run / launch / open the notepad, a windowed based editor program on Windows, Similarly we can lunch other program by passing the proper name of the program which we suppose to lunch in programmatic way.

Sometimes we have to pass full path name of the external program, for example, c:/windows/program file/notepad.exe (We can also use backslashes, but be careful to put double slashes because the backslash is special in Java strings) if the corresponding external program is not included in operating systems global variable pool[Path is not set] in order to get lunched / recognized through system call from anywhere.

In windows, by using command prompt, go to the directory where above program is present in the form of a java file and pass command as mentioned below:

javac LunchExternalProg.java – To Compile.

java LunchExternalProg – To Run.

Related posts