Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

java - ProcessBuilder adds extra quotes to command line

I need to build the following command using ProcessBuilder:

"C:Program FilesUSBDeviewUSBDeview.exe" /enable "My USB Device"

I tried with the following code:

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

ProcessBuilder processBuilder = new ProcessBuilder(test);                       
processBuilder.start().waitFor();   

However, this passes the following to the system (verified using Sysinternals Process Monitor)

"C:Program FilesUSBDeviewUSBDeview.exe" "/enable "My USB Device""

Note the quote before /enable and the two quotes after Device. I need to get rid of those extra quotes because they make the invocation fail. Does anyone know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 FilesUSBDeviewUSBDeview.exe" "/enable "My USB Device"", which may do the trick; YMMV.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...