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

2020-03-27 04:05发布

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 in. Would

file://./folder/file.file

work correctly, or,

jar:file://./!hello.jar/folder/file.file

or is there an easier way to do this?

(Sorry for the dumb question, I'm new to maven.)

标签: java url
2条回答
Melony?
2楼-- · 2020-03-27 04:40

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.

查看更多
看我几分像从前
3楼-- · 2020-03-27 04:42

You can find a jar's resources by using:

String resRelativePath = "folder/thing.jpg";
URL resUrl = this.getClass().getResource(resRelativePath);
查看更多
登录 后发表回答