Guilherme Ruiz Guilherme Ruiz - 2 months ago 11
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

1)

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


2)

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
/home/user/
, it returns
/home/user/MyJar.jar
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.

Ex:
/home/user/Documents/test%20folder/MyJar.jar


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

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());
    System.out.println(f.getAbsolutePath());
} catch (URISyntaxException ex) {
    throw new RuntimeException(ex);
}

(Only tested under Linux)

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

Comments