Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

linux

jar

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?

like image 864
Guilherme Ruiz Avatar asked Dec 06 '25 03:12

Guilherme Ruiz


1 Answers

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)

like image 78
Moose Morals Avatar answered Dec 07 '25 17:12

Moose Morals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!