Drudge
Drudge

Reputation: 528

Java ProcessBuilder ignores Whitespaces

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.

Upvotes: 2

Views: 1648

Answers (1)

Ruslan Ostafiichuk
Ruslan Ostafiichuk

Reputation: 4712

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

    list.add("\"C:\\Program Files (x86)\\TightVNC\\tvnserver.exe\" -controlservice -connect 172.20.242.187");

Upvotes: 2

Related Questions