3

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?

user2248702
  • 2,741
  • 7
  • 41
  • 69
  • replacing %20 back to actual spaces should work. They are result of url encoding. Edit: See http://stackoverflow.com/a/12733172/995891 – zapl Dec 02 '14 at 03:39
  • Can you include the full error you're getting, including stack trace? What OS are you running this on? And the actual `command` string? It is tokenized in this form of Runtime.exec(), so there could be issues there. – Andrew Janke Dec 02 '14 at 03:40
  • @AndrewJanke The command I am running does not seem to make any difference. I haved tried this on both Windows 7 and Linux (Ubuntu) and it also does not seem to make any difference. I am just passing a string for the command. – user2248702 Dec 02 '14 at 03:48
  • Okay. Then it's probably just a matter of decoding the URL path to get the right `jarLocation`. See answer I posted. – Andrew Janke Dec 02 '14 at 03:49

1 Answers1

1

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.

Community
  • 1
  • 1
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85