ProcessBuilder adds extra quotes to command line

混江龙づ霸主 提交于 2019-11-28 01:52:03

As far as I understand, since ProcessBuilder has no idea how parameters are to be passed to the command, you'll need to pass the parameters separately to ProcessBuilder;

ArrayList<String> test = new ArrayList<String>();
test.add("\"C:\\Program Files\\USBDeview\\USBDeview.exe\"");
test.add("/enable");
test.add("\"My USB Device\"");

Joachim is correct, but his answer is insufficient when your process expects unified arguments as below:

myProcess.exe /myParameter="my value"

As seen by stefan, ProcessBuilder will see spaces in your argument and wrap it in quotes, like this:

myProcess.exe "/myParameter="my value""

Breaking up the parameter values as Joachim recommends will result in a space between /myparameter= and "my value", which will not work for this type of parameter:

myProcess.exe /myParameter= "my value"

According to Sun, in their infinite wisdom, it is not a bug and double quotes can be escaped to achieve the desired behavior.

So to finally answer stefan's question, this is an alternative that SHOULD work, if the process you are calling does things correctly:

ArrayList<String> test = new ArrayList<String>();
test.add("\"C:\\Program Files\\USBDeview\\USBDeview.exe\"");
test.add("/enable \\\"My USB Device\\\"");

This should give you the command "C:\Program Files\USBDeview\USBDeview.exe" "/enable \"My USB Device\"", which may do the trick; YMMV.

First, you need to split up the arguments yourself - ProcessBuilder doesn't do that for you - and second you don't need to put escaped quotes around the argument values.

ArrayList<String> test = new ArrayList<String>();
test.add("C:\\Program Files\\USBDeview\\USBDeview.exe");
test.add("/enable");
test.add("My USB Device");

The quotes are necessary on the command line in order to tell the cmd parser how to break up the words into arguments, but ProcessBuilder doesn't need them because it's already been given the arguments pre-split.

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