2

I try to start a program via the Windows command shell out of Java and experience errors I cannot solve myself. I use a ProcessBuilder to pass the arguments to the command shell.

Snippet:

try{
        List<String> list = new ArrayList<String>();
        list.add("cmd.exe");
        list.add("/c");
        list.add("C:\\Program Files (x86)\\TightVNC\\tvnserver.exe -controlservice -connect 172.20.242.187");
        ProcessBuilder builder = new ProcessBuilder(list);
        System.out.println(builder.command());
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while(true){
            line = r.readLine();
            if(line == null) { break; }
            System.out.println(line);
        }
} catch {...}

My problem is that the whitespaces in the path to the program are ignored. Console output:

[cmd.exe, /c, C:\Program Files (x86)\TightVNC\tvnserver.exe -controlservice -connect 172.20.242.187] Der Befehl "C:\Program" ist entweder falsch geschrieben oder konnte nicht gefunden werden.

(C:\Program cannot be found).

On the web i found similar problems even on StackOverflow and other websites did it exactly as I did, see an example at Run cmd commands through java with the difference I passed the arguments as a list mentioned in http://www.tutorialspoint.com/java/lang/processbuilder_command_list.htm

So I do not understand why my command is not working. I appreciate any help

Edit I have to add the path dynamically so I cannot pass the arguments when creating the ProcessBuilder object.

Community
  • 1
  • 1
Drudge
  • 508
  • 5
  • 19
  • Try to add double qoutes arround `"\"C:\\Program Files (x86)\\TightVNC\\tvnserver.exe\" -controlservice -connect ` 172.20.242.187" – Jens Dec 09 '14 at 08:20

1 Answers1

2

Double quotes (\") are required if your path contains whitespaces:

    list.add("\"C:\\Program Files (x86)\\TightVNC\\tvnserver.exe\" -controlservice -connect 172.20.242.187");
Ruslan Ostafiichuk
  • 3,584
  • 6
  • 27
  • 35
  • Thanks, that did it for me! I tried it that way too but also hat the parameters in the \" Thank you! – Drudge Dec 09 '14 at 08:24