java get jar execution directory

java get jar execution directory

To get the execution directory of a Java jar file, 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 execution directory of the current jar file:

String executionDirectory;
try {
    URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
    executionDirectory = new File(url.toURI()).getParent();
} catch (URISyntaxException e) {
    executionDirectory = null;
}
Sou‮www:ecr‬.lautturi.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 getParent method returns the parent directory of the File object, which is the execution directory of the jar file.

Note that this approach assumes that the current class (Main in this example) is contained in the jar file whose execution directory you want to get. If you want to get the execution directory 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