Java ProcessBuilder ignores Whitespaces

蓝咒 提交于 2020-05-15 08:09:04

问题


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.


回答1:


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

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


来源:https://stackoverflow.com/questions/27374195/java-processbuilder-ignores-whitespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!