Starting a Java tool with cmd.exe

2019-09-05 18:03发布

问题:

I am trying to start a Java command line tool in its own cmd.exe window from Java. I use ProcessBuilder to start the following:

cmd.exe /k "C:\Program Files (x86)\JavaSoft\jre\1.5.0_07\bin\java.exe"

This works. This also works:

cmd.exe /k "C:\Program Files (x86)\JavaSoft\jre\1.5.0_07\bin\java.exe" -version

But when I try to run the following

cmd.exe /k "C:\Program Files (x86)\JavaSoft\jre\1.5.0_07\bin\java.exe" "test a"

I get an error saying it can't find "C:\Program". I expected to get an exception from java.exe. I need to be able to use quotation marks in some of the arguments. Is there any way to do this?

回答1:

From "cmd /?":

  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.

Okay, that explains why it doesn't work if there are more than two quotes. But that doesn't explain how exactly to solve the problem. Thankfully, Google has the answer:

cmd.exe /k ""d:\laj soft\java.exe" "test a""


回答2:

Try following:

java -jar your_jar_archive.jar



回答3:

If you have control over where your JDK is installed, its a good idea to install it in a location that does not contain spaces. "Program Files" is the default location on Windows but it almost always leads to problems.



回答4:

You could try to use the old DOS trick for this one. Refer to Program Files as progra~1. This usually gets me around the problem.



标签: java cmd