如何获取当前正在运行的jar的路径和名称? [英] How to get the path and name of the current running jar?

查看:135
本文介绍了如何获取当前正在运行的jar的路径和名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多文件夹可以让您找到正在运行的jar所在的文件夹,但是如何获取正在运行的jar?例如,如果foo.jar位于C:/FOO/foo.jar中,那么我将如何获取路径C:/FOO/foo.jar,而不是C:/FOO.另外,我也不知道A:如果将jar移到了另一个文件夹,B:如果我的jar被重命名,C:如果我的文件夹中还有其他jar.我想获取当前正在运行的jar的File对象,然后使用(以某种方式)用我程序的新版本替换该jar.谁能帮我这个?谢谢! 请稍等,找到目录后,是否可以浏览目录以查找jar文件,然后在每个jar文件中检查我的jar中是否有某个特定的类/其他文件?

There are plenty of folders that let you find the folder that the running jar is in, but how do I get the running jar? For example, if foo.jar is in C:/FOO/foo.jar, then how would I get the path C:/FOO/foo.jar, not C:/FOO. Also, I have no idea A: if the jar was moved to a different folder, B: If my jar was renamed, and C: if there are other jars in the same folder as mine. I want to get a File object of the currently running jar, which I am then going to be using (in some way) to replace that jar with a new version of my program. Can anyone help me with this? Thanks! Wait a minute, would it be possible to, after finding the directory, scan through it looking for jar files, and in each jar file, check for a certain class/other file that is in my jar?

推荐答案

好的,我知道了.就像这样:

Alright, I got it figured out. It's something like this:

File dir = new File(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
String jar = System.getProperty("java.class.path");
File jarFile = new File(dir, jar);

谢谢大家! 而且,如果我最终在类路径中遇到多个jar,我将需要一些检查来确保我得到了正确的jar.

Thanks everyone! Also, if I ever end up with multiple jars in the classpath, I would need something to check that I got the right one.

这篇关于如何获取当前正在运行的jar的路径和名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆