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

查看:127
本文介绍了获取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:\Users\Kevin\Desktop/server/Server


b $ b

,而JAR文件位于

while the JAR file is located at

C:\Users\Kevin\Desktop

我也尝试过

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

但这会返回:

C:\Users\Kevin\Desktop\server.jar/server/Server

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

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

任何方式这样做?

推荐答案

这应该起作用

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:\Users\User01\Documents\app1\dist\JavaApplication1.jar

并返回

C:\Users\User01\Documents\app1\dist

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

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