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?
That
getPath()
call, which isURL.getPath()
, does not return a filesystem path. It returns the path portion of a URL. In the case of afile:
URL, it will be a URL-encoded local filesystem path. If that original URL is in fact afile:
URL, you need to use the URI and URL classes, or custom string processing, to convert that to a local filesystem path that theRuntime.exec()
can work with.This might work directly in your case.
You can also see the discussion at Converting Java file:// URL to File(...) path, platform independent, including UNC paths.