Loading a file relative to the executing jar file

后端 未结 2 887
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 08:27

The question says it all.

The specialty in my case is that the current working directory is not the location of the jar file but c:\\Windows\\system32 (

相关标签:
2条回答
  • 2020-12-03 08:35

    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.

    0 讨论(0)
  • 2020-12-03 08:40

    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.
    
    0 讨论(0)
提交回复
热议问题