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

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


当前回答

这个方法从存档中的代码中调用,返回.jar文件所在的文件夹。它应该在Windows或Unix中工作。


  private String getJarFolder() {
    String name = this.getClass().getName().replace('.', '/');
    String s = this.getClass().getResource("/" + name + ".class").toString();
    s = s.replace('/', File.separatorChar);
    s = s.substring(0, s.indexOf(".jar")+4);
    s = s.substring(s.lastIndexOf(':')-1);
    return s.substring(0, s.lastIndexOf(File.separatorChar)+1);
  } 

从下面的代码派生:确定是否从JAR运行

其他回答

对我来说,在Linux、Mac和Windows上都适用的唯一解决方案是:

public static String getJarContainingFolder(Class aclass) throws Exception {
  CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();

  File jarFile;

  if (codeSource.getLocation() != null) {
    jarFile = new File(codeSource.getLocation().toURI());
  }
  else {
    String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
    String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
    jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
    jarFile = new File(jarFilePath);
  }
  return jarFile.getParentFile().getAbsolutePath();
}

我很惊讶地发现,最近没有人建议使用Path。以下是引用:“Path类包括各种方法,可用于获取路径信息、访问路径元素、将路径转换为其他形式或提取路径的部分”

因此,一个好的替代方法是获取Path对象为:

Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());

为了获得运行jar文件的路径,我研究了上述解决方案,并尝试了各种方法,它们之间存在一些差异。如果这些代码在Eclipse IDE中运行,它们都应该能够找到包含指定类的文件路径,并使用找到的路径打开或创建指定的文件。

但这很棘手,当直接或通过命令行运行可运行的jar文件时,它将失败,因为从上述方法获得的jar文件的路径将在jar文件中给出一个内部路径,也就是说它总是给出一个路径

rsrc:project-name(也许我应该说它是主类文件的包名-指定的类)

我不能转换rsrc:…路径到外部路径,即当在Eclipse IDE外部运行jar文件时,无法获得jar文件的路径。

在Eclipse IDE之外获取运行jar文件的路径的唯一可能方法是

System.getProperty("java.class.path")

这段代码行可能返回的生活路径(包括文件名)运行jar文件(注意,返回路径不是工作目录),作为java文档,有些人说,它将返回所有类文件在同一个目录的路径,但随着我的测试中,如果在相同的目录中包括许多jar文件,它只返回运行jar的路径(约多条路径问题确实发生在Eclipse)。

这段代码对我很有用:

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;
  }

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


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