Loading a file relative to the executing jar file
Solution 1:
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.
Solution 2:
To get Launcher.class.getResourceAsStream("/../config.xml")
to work, you need to add its path to the Class-Path
entry of the JAR's MANIFEST.MF
file. This is the normal practice.