Guilherme Ruiz Guilherme Ruiz - 1 year ago 94
Linux Question

How do I get path with spaces to current executing jar with java command in Linux?

I have two methods to obtain the jar path


File file = new File(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName());
String filename = file.getAbsolutePath().toString();


String filename2 = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);

The first method works perfectly for windows and Mac, but in linux, if my jar is located at
'/home/user/Documents/test folder/'
, it returns my current working directory + the jar file

Ex: If my terminal is at
, it returns
even though MyJar.jar path is
'/home/user/Documents/test folder/'

The second method, for every operational system returns the correct path to the file but with spaces replaced by %20.


How can I get the absolute path in Linux the same way I do for windows and Mac, and without %20 as space replacement?

Answer Source

I'm not sure why you've double wrapped your File's in the first solution.

try {
    File f = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException ex) {
    throw new RuntimeException(ex);

(Only tested under Linux)

(I don't think the URISyntaxException will ever be thrown in production)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download