Search code examples
javacommand-lineprocessbuilder

ProcessBuilder does not work with argument


I'm writing a program, one of the functions it clicking on a cell in the table with the name of the computer of a user, in the command line, a external program is called to connect to the computer remotely. The command looks like this:

"C:\Program Files\Vnc\MegaVNC\vncviewer.exe" /user vncadmin /password xxxxxx /server comp-01

"C:\Program Files\Vnc\MegaVNC\vncviewer.exe" is the location of the file, and "/ user vncadmin /password xxxxxx /server comp-01" argument. Please note that argument is written without quotes. When you call this command from the command line, everything works.

My code with ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe ",  "/user vncadmin /password xxxxxx /server comp-01").start();

But it does not work. If you remove the argument, the called program is opened. But when initializing with an argument, the program itself hangs on the argument and the connection crashes. I tried the following:

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe", "/user vncadmin ", "/password xxxxxx ", "/server comp-01").start();

It does not work either. I guess that the problem is in the wrong interpretation compiler of the slash or spaces. Any thoughts?


Solution

  • You should pass all command line arguments as separate parameters to the process builder. Otherwise, they are internally quoted and therefore interpreted as a single argument by the called program.

    ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe", "/user", "vncadmin", "/password", "xxxxxx", "/server", "comp-01").start();
    

    I created a stupid batch "C:/Temp/test.bat":

    @echo off
    set argCount=0
    for %%x in (%*) do (
       set /A argCount+=1
       echo %%x
    )
    echo Number of processed arguments: %argCount%
    

    With new ProcessBuilder("C:/Temp/test.bat", "a b").start();, I got result:

    "a b"
    Number of processed arguments: 1
    

    With new ProcessBuilder("C:/Temp/test.bat", "a", "b").start();, I got result:

    a
    b
    Number of processed arguments: 2