如何获取正在运行的 JAR 文件的路径? [英] How to get the path of a running JAR file?

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

问题描述

我的代码在 JAR 文件中运行,比如 foo.jar,我需要知道在代码中运行的 foo.jar 位于哪个文件夹中.

My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.

因此,如果 foo.jarC:\FOO\ 中,无论我当前的工作目录是什么,我都想获得该路径.

So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.

推荐答案

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

将MyClass"替换为您班级的名称.

Replace "MyClass" with the name of your class.

显然,如果您的类是从非文件位置加载的,这会产生奇怪的效果.

Obviously, this will do odd things if your class was loaded from a non-file location.

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

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