java runtime.exec cmd /c parsing quoted arguments

2019-06-05 05:30发布

问题:

I'm trying to run runtime.exec(String[],null, new File(directory)) with the first two arguments being "cmd" and "/c".

I'm trying to specify the version of java for my tomcat to run. It appears that the cmd /c arguments are causing runtime.exec to parse all of the arguments by space delineation or probably more appropriately cmd is parsing each argument out.

So,

cmd /c .\bin\Tomcat7.exe //US//Tomcat7 --Jvm="C:\Program Files\Apache Tomcat 7\jre\bin\server\jvm.dll"

is getting the jvm argument broken into arguments "C:\Program", "Files\Apache","Tomcat..... which is causing to not be able to interpret the arguments. Quoting the arguments appears to being ignored as well.

Is there a way to either make quoting the jvm argument be respected by cmd or to utilize the specified directory in the runtime.exec?

Thanks for reading.

回答1:

an efficient workaround is to use windows short names:

replace Program Files by PROGRA~1 (use DIR /X C:\ | find "Program") to see if it is the correct name

replace Apache Tomcat 7 by APACHE~1 (or whatever is returned by DIR /X C:\PROGRA~1 | find "Apache")

Your command is very likely to be

cmd /c .\bin\Tomcat7.exe //US//Tomcat7 --Jvm=C:\PROGRA~1\APACHE~1\jre\bin\server\jvm.dll

no more spaces: problem solved

EDIT:

unverified, but you may want to try this flavour of exec instead:

public Process exec(String command, String[] envp, File dir);

like this:

exec("cmd /c .\bin\Tomcat7.exe //US//Tomcat7 --Jvm=\"C:\Program Files\Apache Tomcat 7\jre\bin\server\jvm.dll\"",null,new File(directory))

The API you're currently using has to rebuild the full command line from your parameters, which are not really parameters, but rather groups of parameters with spaces, quotes, etc... It is possible (unchecked) that the API tries to add quotes where it's not needed, thus corrupting your command line.