获取 JAR 文件的位置 [英] Get location of JAR file

查看:17
本文介绍了获取 JAR 文件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取运行 Runnable JAR 文件的位置.我试着做

I'm trying to get the location a Runnable JAR file is run from. I tried doing

try {
    String path = new java.io.File(".").getCanonicalPath();
} catch (IOException e) {
    e.printStackTrace();
}

但这会返回:

C:UsersKevinDesktop/server/Server

而 JAR 文件位于

C:UsersKevinDesktop

我也尝试过

return new file(Server.class.getProtectionDomain().getCodeSource().getLocation().getPath());

但这会返回:

C:UsersKevinDesktopserver.jar/server/Server

所以基本上我想要没有文件名的 JAR 文件的路径,而不是 ClassPath.

So basicly I want the path of the JAR file without the filename and not the ClassPath.

有什么办法吗?

推荐答案

更新

由于它在某些测试用例中不起作用,我会更新答案.

Since it doesn't work in certain test-cases, I'll update the answer.

正确的做法应该是使用ClassLoader:

The correct way to do this should be with ClassLoader:

File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
System.out.println(jarDir.getAbsolutePath());

在各种类路径上测试,输出是正确的.

Tested on various classpaths, the output was correct.

旧答案

这应该有效

File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();

它对我有用,我的程序在:

It works for me, my program is in:

C:UsersUser01Documentsapp1distJavaApplication1.jar

然后它返回

C:UsersUser01Documentsapp1dist

这篇关于获取 JAR 文件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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