简体   繁体   中英

java ProcessBuilder in Windows spaces in *.exe path and in argument

often discussed, but this seems a weired edge case.

In win cmd.exe I successfully run:

"c:\Program Files\myapp.exe" -my_arg="sth. with space"

and

"c:\Program Files\myapp.exe" -my_arg="sth_without_space"

in java ProcessBuilder.command(xxx) following fails with "c:\Program" was not a valid command (xxx contains following array):

// using cmd.exe:
["cmd.exe", "/c", "c:\Program Files\myapp.exe", "-my_arg=sth. with space"]         // no extra quoting
["cmd.exe", "/c", "\"c:\Program Files\myapp.exe\"", "-my_arg=sth. with space"]     // exe       quoted
["cmd.exe", "/c", "\"c:\Program Files\myapp.exe\"", "-my_arg=\"sth. with space\""] // exe & arg quoted
["cmd.exe", "/c", "c:\Program Files\myapp.exe", "-my_arg=\"sth. with space\""]     //       arg quoted

// putting all as cmd.exe arg:
["cmd.exe", "/c", "c:\Program Files\myapp.exe -my_arg=sth. with space"]            // no extra quoting
["cmd.exe", "/c", "\"c:\Program Files\myapp.exe\" -my_arg=sth. with space"]        // exe       quoted
["cmd.exe", "/c", "\"c:\Program Files\myapp.exe\" -my_arg=\"sth. with space\""]    // exe & arg quoted
["cmd.exe", "/c", "c:\Program Files\myapp.exe -my_arg=\"sth. with space\""]        //       arg quoted

// calling *.exe directly
["c:\Program Files\myapp.exe", "-my_arg=sth. with space"]                          // no extra quoting
["\"c:\Program Files\myapp.exe\"", "-my_arg=sth. with space"]                      // exe       quoted
["\"c:\Program Files\myapp.exe\"", "-my_arg=\"sth. with space\""]                  // exe & arg quoted
["c:\Program Files\myapp.exe", "-my_arg=\"sth. with space\""]                      //       arg quoted

running this works fine:

["cmd.exe", "/c", "c:\Program Files\myapp.exe", "-my_arg=sth_without_space"]

The issues seem to start when the *.exe path and the arg contain whitespaces.

[edit]: My question is: How can you run it with whitespaces in the exe's path AND in the arg's content?

To make it work WITH cmd and WITH spaces you need to add yet another layer of quoting.

After all you write a java program. The java compiler will expect strings to be quoted, but at runtime these quotes are no longer there. Some of the strings will be used to start cmd, others will be passed on to cmd.

Cmd itself checks the arguments it received and will parse them. To markup which whitespace is a delimiter and which is not you need to have quotes. Cmd will understand these quotes and remove them - the called program does not notice them any more.

So either add more quotes (with correct escaping) or try to run the executable directly.

["cmd.exe", "/c", "\"c:\\Program Files\\myapp.exe\"", "\"-my_arg=sth_with space\""]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM