W3docs

How to get the path of a running JAR file?

To get the path of a running JAR file, you can use the java.lang.Class class's getProtectionDomain method and then the getCodeSource method.

To get the path of a running JAR file, you can use the java.lang.Class class's getProtectionDomain method and then the getCodeSource method.

Here is an example of how to do this:


ProtectionDomain domain = MyClass.class.getProtectionDomain();
String path = (domain != null && domain.getCodeSource() != null)
    ? domain.getCodeSource().getLocation().toURI().getPath()
    : null;

This will return the path of the JAR file containing the MyClass class. You can use this technique in any class within your JAR file.

This technique works for both executable JARs and libraries, provided the class is loaded from a JAR file. Note that in Java 9+, if the class is loaded from the module path, getProtectionDomain() may return null.

If you want to get the directory containing the JAR file, you can use the following technique:


ProtectionDomain domain = MyClass.class.getProtectionDomain();
String jarDir = null;
if (domain != null && domain.getCodeSource() != null) {
    String path = domain.getCodeSource().getLocation().toURI().getPath();
    jarDir = new File(path).getParentFile().getAbsolutePath();
}

This will give you the directory that the JAR file is located in.

I hope this helps! Let me know if you have any questions.