Windows java.exe -jar with spaces

910 views Asked by At

I know there are already dozens of questions out there about dealing with executing system commands that have paths with spaces in Java, but I've not found a solution to my exact situation yet.

I'm using java.exe that comes with jdk-1.8.x on a Windows 10 computer. The command I want to execute is as follows (I will want to use ProcessBuilder from within a Java program eventually, but my problem doesn't hinge on the command being executed that way; it persists if I type it directly into a terminal as well):

cmd.exe /C "G:\myself\...\My Folder\...\runtime\bin\java.exe" -jar "G:\myself\...\My Folder\...\application.jar" <app_args>

Both paths include My Folder, a directory with a space in its name. However, the path to java.exe works, but the path to application.jar does not.

I know the first path works because I can run:

cmd.exe /C "...\java.exe" -version

But when I attempt to run the second one the error is:

'G:\myself\...\My' is not recognized as an internal or external command, operable program or batch file.

What is going on here? Why is the path for java working, while the path for the jar is not? Does java.exe -jar <jar_path> parse the jar path differently than the terminal parses the java path?

1

There are 1 answers

3
Dai On BEST ANSWER

You're not running java.exe directly - you're running cmd.exe and then instructing cmd.exe to start java.exe, and that's what's messing with your handling of command-line arguments.

When using cmd.exe /C, you need to pass it a single long quoted string, so you need to escape the double-quotes by doubling them up (confusingly, in this mode, single double-quote characters do not need escaping, only the leading and following quotes - it's confusing and inconsistent ("it's confusing and inconsistent" pretty much summarizes the entire Windows command-line system, but that's another story).

Try this:

cmd.exe /C ""G:\myself\...\My Folder\...\runtime\bin\java.exe" -jar "G:\myself\...\My Folder\...\application.jar" "<app_args>""

For PowerShell

PowerShell is great once you get used to it (and I still haven't gotten used to it), but it's annoyingly different to the normal Windows command-line for starting other programs - simply typing the name of an executable in PowerShell will not run it, you need to use either the long-term Start-Process or use dot-slash ./ (the same as Bash):

From How to call a Java program from PowerShell?

Start-Process java.exe -ArgumentList '-jar', 'G:\myself\...\My Folder\...\application.jar'