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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With