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

所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。


当前回答

如果您确实在寻找一种获取JAR所在文件夹的简单方法,那么您应该使用这个实现。 像这样的解决方案很难找到,许多解决方案不再受支持,许多其他解决方案提供文件的路径,而不是实际的目录。这比您将要找到的其他解决方案更容易,并且适用于java版本1.12。

new File(".").getCanonicalPath()

从其他答案中收集输入,这也是一个简单的答案:

String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\"; 

两者都会返回如下格式的String:

"C:\Users\User\Desktop\Folder\"

用简洁明了的线条。

其他回答

上述方法在我的Spring环境中并不适用,因为Spring将实际的类隐藏到一个名为BOOT-INF的包中,因此不是运行文件的实际位置。我发现了另一种方法来检索运行文件通过权限对象已授予运行文件:


public static Path getEnclosingDirectory() {
    return Paths.get(FileUtils.class.getProtectionDomain().getPermissions()
            .elements().nextElement().getName()).getParent();
}

这段代码对我很有用:

private static String getJarPath() throws IOException, URISyntaxException {
    File f = new File(LicensingApp.class.getProtectionDomain().().getLocation().toURI());
    String jarPath = f.getCanonicalPath().toString();
    String jarDir = jarPath.substring( 0, jarPath.lastIndexOf( File.separator ));
    return jarDir;
  }

不太确定其他人,但在我的情况下,它不与“可运行的罐子”,我得到了它的工作通过修复代码一起从phchen2答案和另一个从这个链接:如何获得一个运行的jar文件的路径? 代码:

               String path=new java.io.File(Server.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
          .getAbsolutePath();
       path=path.substring(0, path.lastIndexOf("."));
       path=path+System.getProperty("java.class.path");

我用Java 7编写,用Oracle的运行时在Windows 7上测试,用开源运行时在Ubuntu上测试。这对于这些系统来说是完美的:

任何正在运行的jar文件的父目录的路径(假设调用这段代码的类是jar存档本身的直接子目录):

try {
    fooDir = new File(this.getClass().getClassLoader().getResource("").toURI());
} catch (URISyntaxException e) {
    //may be sloppy, but don't really need anything here
}
fooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String

因此,foo.jar的路径是:

fooPath = fooDirPath + File.separator + "foo.jar";

同样,这也没有在任何Mac或旧版本的Windows上进行测试

如果您确实在寻找一种获取JAR所在文件夹的简单方法,那么您应该使用这个实现。 像这样的解决方案很难找到,许多解决方案不再受支持,许多其他解决方案提供文件的路径,而不是实际的目录。这比您将要找到的其他解决方案更容易,并且适用于java版本1.12。

new File(".").getCanonicalPath()

从其他答案中收集输入,这也是一个简单的答案:

String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\"; 

两者都会返回如下格式的String:

"C:\Users\User\Desktop\Folder\"

用简洁明了的线条。