java get location of jar file

java get location of jar file

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;
}
Sourc‮l.www:e‬autturi.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.

Created Time:2017-11-03 22:21:10  Author:lautturi