当前位置: 首页 > 知识库问答 >
问题:

获取JAR文件的位置

凌翔宇
2023-03-14

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

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文件的路径,而不是类路径,而不是文件名。

有办法吗?

共有3个答案

夹谷鸿福
2023-03-14

在我最终找到一个有效的解决方案之前,我不得不胡思乱想了很多
可能jarLocation带有前缀,如file:\jar:file\,可以使用String#substring()删除。

URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
刘德义
2023-03-14

下面是我计算jar目录的版本

/**
 * Compute the absolute file path to the jar file.
 * The framework is based on http://stackoverflow.com/a/12733172/1614775
 * But that gets it right for only one of the four cases.
 * 
 * @param aclass A class residing in the required jar.
 * 
 * @return A File object for the directory in which the jar file resides.
 * During testing with NetBeans, the result is ./build/classes/,
 * which is the directory containing what will be in the jar.
 */
public static File getJarDir(Class aclass) {
    URL url;
    String extURL;      //  url.toExternalForm();

    // get an url
    try {
        url = aclass.getProtectionDomain().getCodeSource().getLocation();
          // url is in one of two forms
          //        ./build/classes/   NetBeans test
          //        jardir/JarName.jar  froma jar
    } catch (SecurityException ex) {
        url = aclass.getResource(aclass.getSimpleName() + ".class");
        // url is in one of two forms, both ending "/com/physpics/tools/ui/PropNode.class"
        //          file:/U:/Fred/java/Tools/UI/build/classes
        //          jar:file:/U:/Fred/java/Tools/UI/dist/UI.jar!
    }

    // convert to external form
    extURL = url.toExternalForm();

    // prune for various cases
    if (extURL.endsWith(".jar"))   // from getCodeSource
        extURL = extURL.substring(0, extURL.lastIndexOf("/"));
    else {  // from getResource
        String suffix = "/"+(aclass.getName()).replace(".", "/")+".class";
        extURL = extURL.replace(suffix, "");
        if (extURL.startsWith("jar:") && extURL.endsWith(".jar!"))
            extURL = extURL.substring(4, extURL.lastIndexOf("/"));
    }

    // convert back to url
    try {
        url = new URL(extURL);
    } catch (MalformedURLException mux) {
        // leave url unchanged; probably does not happen
    }

    // convert url to File
    try {
        return new File(url.toURI());
    } catch(URISyntaxException ex) {
        return new File(url.getPath());
    }
}
公冶桐
2023-03-14

使现代化

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

正确的方法应该是使用ClassLoader

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

在不同的类路径上测试,结果是正确的。

老生常谈

这应该管用

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

它为我工作,我的程序在:

C:\Users\User01\Documents\app1\dist\JavaApplication1.jar

然后它返回

C:\Users\User01\Documents\app1\dist
 类似资料:
  • 问题内容: 假设我在目录 e中 有一个python文件,如下所示: /a/b/c/d/e/file.py 在目录 e下, 我有几个文件夹要访问,但是如果从其他任何地方而不是从文件夹 e 执行file.py,则相对路径对我来说不起作用。另外,文件夹 e 可以位于任何位置,但总是与一组子文件夹一起使用,因此绝对路径将不起作用。 首先,有什么功能可以获取相对于源文件位置的绝对路径? 如果没有,有什么想法

  • 启动jar时,控制台会说找不到文件,也没有加载字体。我怎样才能解决这个问题? 我得到了这个密码:

  • 问题内容: 当我在eclipse中导出可执行jar文件时,也需要使用res文件夹进行编译,当我使用不起作用的方法时。 当前读取的图像代码 代码无效 问题答案: 我现在已经解决了问题-这是有效的代码 fileName的值只是一个图像名称,例如BufferedImage img = loadImage(“ background.png”); 感谢大家的帮助。

  • 问题内容: 我有一个提供文件(包括文件名)的绝对路径的文件。我只想获取文件名。最简单的方法是什么? 必须尽可能地笼统,因为我无法事先知道该URL是什么。我不能简单地创建一个URL对象并使用-尽管所有可能的情况都是理想的- 因为它不一定是前缀,它可以是c:/或类似的东西。 问题答案: 要么 请注意,第一个解决方案取决于系统。它仅考虑系统的路径分隔符。因此,如果您的代码在Unix系统上运行并接收Win

  • 我如何使用getResourceAsStream方法获得一个jar的文件(在maven依赖项中)? 我尝试了以下操作,但返回空:

  • 当我在eclipse中导出可执行jar文件时,我需要获取res文件夹进行编译,当我使用方法时,它不起作用。 当前读取图像代码 不起作用的代码