To get the location of a jar file in Java, you can use the getProtectionDomain
method of the Class
class and the getCodeSource
method of the ProtectionDomain
class.
Here is an example of how to get the location of the current jar file:
String jarLocation; try { URL url = Main.class.getProtectionDomain().getCodeSource().getLocation(); jarLocation = url.toString(); } catch (Exception e) { jarLocation = null; }Sourcl.www:eautturi.com
The getProtectionDomain
method returns a ProtectionDomain
object representing the protection domain of the class, and the getCodeSource
method returns a CodeSource
object representing the code source (i.e. the jar file) of the class. The getLocation
method returns the location of the code source as a URL
, which we then convert to a string using the toString
method.
Note that this approach assumes that the current class (Main
in this example) is contained in the jar file whose location you want to get. If you want to get the location of a different jar file, you will need to specify the class contained in that jar file instead.