Search code examples
javaexternal-processrunning-other-programs

Run external app by userinput


So I'm creating a Java program and I want to make it so that you can ask it to open a program. But, here's the catch, I want the program it opens to be taken from the user input, right now I'm trying to change this

try{Process p = Runtime.getRuntime().exec("notepad.exe");}
catch(Exception e1){}

Into something that opens a program that you asked it to open.

Here's an example of what I want:

User: Can you open chrome? Program: Of course, here you go! chrome opens

Could anyone tell me how I would be able to do this?


Solution

  • You can do it in two ways:

    1.By Using Runtime: Runtime.getRuntime().exec(...)

    So, for example, on Windows,

    Runtime.getRuntime().exec("C:\application.exe -arg1 -arg2");
    

    2.By Using ProcessBuilder:

    ProcessBuilder b = new ProcessBuilder("C:\application.exe", "-arg1", "-arg2");
    

    or alternatively

    List<String> params = java.util.Arrays.asList("C:\application.exe", "-arg1", "-arg2");
    ProcessBuilder b = new ProcessBuilder(params);
    

    or

    ProcessBuilder b = new ProcessBuilder("C:\application.exe -arg1 -arg2");
    

    The difference between the two is :

    Runtime.getRuntime().exec(...) takes a single string and passes it directly to a shell or cmd.exe process. The ProcessBuilder constructors, on the other hand, take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument.

    So,Runtime.getRuntime.exec() will pass the line C:\application.exe -arg1 -arg2 to cmd.exe, which runs a application.exe program with the two given arguments. However, ProcessBuilder method will fail, unless there happens to be a program whose name is application.exe -arg1 -arg2 in C:.