My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.
So, if foo.jar is in C:\FOO\
, I want to get that path no matter what my current working directory is.
In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .
In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation() .toURI()).getPath();
Replace "MyClass" with the name of your class.
Obviously, this will do odd things if your class was loaded from a non-file location.
Best solution for me:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8");
This should solve the problem with spaces and special characters.
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