获取程序正在运行的.jar文件的URL [英] Get URL of file in .jar that the program is running
问题描述
给定使用maven编译的hello.jar,我想访问位于folder / file.file下的资源。但是我不知道如何获取我所在的当前JAR的URL。
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
正常工作,或者
jar:file://./!hello.jar/folder/file.file
还是有更简单的方法吗?
or is there an easier way to do this?
(抱歉这个愚蠢的问题,我是maven的新手。)
(Sorry for the dumb question, I'm new to maven.)
推荐答案
这对我有用:
URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
String jarPath = URLDecoder.decode(url.getFile(), "UTF-8");
jarPath
然后包含完整路径带有该代码的类所在的jar文件。
jarPath
then contains the complete path to the jar file where the class with that code is located.
通过URLDecoder注意绕行,否则如果找到jar文件,你将得到一个包含%20的文件名在包含空格的目录中。
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.
这篇关于获取程序正在运行的.jar文件的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!