java 获取程序正在运行的 .jar 文件的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16240353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get URL of file in .jar that the program is running
提问by aLaserShark
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
给定使用 maven 编译的 hello.jar,我想访问位于文件夹/file.file 下的资源。但是我不知道如何获取我所在的当前 JAR 的 URL。会
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.)
(对不起,这个愚蠢的问题,我是 maven 的新手。)
回答by a_horse_with_no_name
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.
jarPath
然后包含具有该代码的类所在的 jar 文件的完整路径。
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.
请注意 URLDecoder 中的“绕行”,否则如果 jar 文件位于包含空格的目录中,您将获得包含 %20 的文件名。
回答by JohnKlehm
You can find a jar's resources by using:
您可以使用以下命令查找 jar 的资源:
String resRelativePath = "folder/thing.jpg";
URL resUrl = this.getClass().getResource(resRelativePath);