关于CMD的小事

当时的情况是这样的,我需要在基于Eclipse 3.6+jre6的RCP中调用一个使用jre1.5工具。通过Runtime.exec(command)的方式执行,这个事儿本事很平淡,简单的调用而已。

生成的命令应该是如下的模样:(因为有名称带空格的文件夹,为了偷懒,我把整个路径都用双引号引上了。)

cmd /c “c:\Programe Files\Java\jdk1.5\bin\java.exe” -jar aaa.jar -name xxx -file “D:\a.file”

这种做法硬是让我碰到了一个棘手的问题:粘贴到CMD窗口里可以正常执行,但是在代码里就是没法运行。没头苍蝇一样google了一通也没找到合理的解决方法。

最终我决定老老实实的把CMD /?里面的东西看看,果然给我找到解决方法了:
这段文字复制自CMD的帮助文档,详细解释了双引号在命令中的用法

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (“) characters:

1. If all of the following conditions are met, then quote characters
on the command line are preserved:

– no /S switch
– exactly two quote characters
– no special characters between the two quote characters,
where special is one of: &<>()@^|
– there are one or more whitespace characters between the
the two quote characters
– the string between the two quote characters is the name
of an executable file.

2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.

我将命令改成如下形状便一切正常了

cmd /c c:\”Programe Files\Java\jdk1.5\bin\java.exe” -jar aaa.jar -name xxx -file “D:\a.file”

这位老兄在stackoverflow的自问自答也很有借鉴意义