To get the path 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 path of the current jar file:
String jarPath; try { URL url = Main.class.getProtectionDomain().getCodeSource().getLocation(); jarPath = new File(url.toURI()).getAbsolutePath(); } catch (URISyntaxException e) { jarPath = null; }Sour.www:eclautturi.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 File
object using the toURI
method and the File
constructor. The getAbsolutePath
method returns the absolute path of the File
object, which is the path of the jar file.
Note that this approach assumes that the current class (Main
in this example) is contained in the jar file whose path you want to get. If you want to get the path of a different jar file, you will need to specify the class contained in that jar file instead.