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

查看:313
本文介绍了获取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

而JAR文件位于

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.

任何方式这样做?

推荐答案

更新

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

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

它返回

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

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

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