Runtime.exec() fails with space in directory (Java)

1.1k Views Asked by At

I am trying to execute a process in the same directory as my Jar file by getting the location of the file with

private static File jarLocation = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile();

then calling

Runtime.getRuntime().exec("command", null, jarLocation);

This usually works just fine but when the path has a space in it I get "The directory name is invalid". I have attempted to add some debug code which prints the path of the directory which has replaced spaces with "%20" (I assume because the ASCII hex of space is 20). is there a way to be able to use a directory with spaces in its path?

1

There are 1 best solutions below

0
On BEST ANSWER

That getPath() call, which is URL.getPath(), does not return a filesystem path. It returns the path portion of a URL. In the case of a file: URL, it will be a URL-encoded local filesystem path. If that original URL is in fact a file: URL, you need to use the URI and URL classes, or custom string processing, to convert that to a local filesystem path that the Runtime.exec() can work with.

This might work directly in your case.

File jarLocation = Paths.get(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toFile();

You can also see the discussion at Converting Java file:// URL to File(...) path, platform independent, including UNC paths.