Loading a file relative to the executing jar file

Here is one possible solution using Class.getProtectionDomain():

final Class<?> referenceClass = YourMainClass.class;
final URL url =
    referenceClass.getProtectionDomain().getCodeSource().getLocation();

try{
    final File jarPath = new File(url.toURI()).getParentFile();
    System.out.println(jarPath); // this is the path you want 
} catch(final URISyntaxException e){
    // etc.
}

YourMainClass can be replaced by any class in your jar.


From the Class.getProtectionDomain() docs:

Returns the ProtectionDomain of this class.
If there is a security manager installed, this method first calls
the security manager's checkPermission method with a
RuntimePermission("getProtectionDomain") permission to ensure it's
ok to get the ProtectionDomain.

Returns:
  the ProtectionDomain of this class
Throws:
  SecurityException - if a security manager exists and its
  checkPermission method doesn't allow getting the ProtectionDomain.

Leave a Comment