java runtime.exec cmd /c parsing quoted arguments

允我心安 提交于 2019-12-08 07:17:22

问题


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.



来源:https://stackoverflow.com/questions/39044114/java-runtime-exec-cmd-c-parsing-quoted-arguments

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