Get URL of file in .jar that the program is running

后端 未结 2 769
北荒
北荒 2021-01-15 06:19

Given hello.jar, which is compiled with maven, I want to access a resource located under folder/file.file. However I don\'t know how to get the URL of the current JAR I am i

相关标签:
2条回答
  • 2021-01-15 07:05

    You can find a jar's resources by using:

    String resRelativePath = "folder/thing.jpg";
    URL resUrl = this.getClass().getResource(resRelativePath);
    
    0 讨论(0)
  • 2021-01-15 07:07

    This works for me:

    URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
    String jarPath = URLDecoder.decode(url.getFile(), "UTF-8");
    

    jarPath then contains the complete path to the jar file where the class with that code is located.

    Note the "detour" through URLDecoder, otherwise you'll get a filename containing %20 if the jar files is located in a directory that contains spaces.

    0 讨论(0)
提交回复
热议问题