经常讨论,但这似乎是一个奇怪的边缘情况。
在win cmd.exe中,我成功运行:
"c:\Program Files\myapp.exe" -my_arg="sth. with space"
和/或
"c:\Program Files\myapp.exe" -my_arg="sth_without_space"
在java ProcessBuilder中,以下命令(xxx)失败,“c:\Program”不是有效的命令(xxx包含以下数组):
// 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
运行此命令可以正常工作:
["cmd.exe", "/c", "c:\Program Files\myapp.exe", "-my_arg=sth_without_space"]
当 *.exe路径和参数包含空格时,问题似乎就开始了。
[edit]:我的问题是:你怎么能运行它与空格在exe的路径和在arg的内容?
1条答案
按热度按时间huwehgph1#
要使它与cmd和WITH空格一起工作,您需要添加另一个引用层。
毕竟你写的是一个java程序。java编译器将期望字符串被引号括起来,但在运行时这些引号不再存在。其中一些字符串将用于启动cmd,其他字符串将传递给cmd。
Cmd本身检查它收到的参数并将解析它们。要标记哪些空格是分隔符,哪些不是,您需要使用引号。Cmd将理解这些引号并将其删除-被调用的程序不再注意到它们。
因此,要么添加更多的引号(使用正确的转义),要么尝试直接运行可执行文件。