我的代码在一个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\"

用简洁明了的线条。

其他回答

我已经尝试了上面的几种解决方案,但是对于在Eclipse中使用“打包外部库”导出可运行jar的情况(可能是特殊情况),没有一个产生正确的结果。出于某种原因,所有基于ProtectionDomain的解决方案在这种情况下都将导致null。

通过结合上面的一些解决方案,我成功地实现了以下工作代码:

String surroundingJar = null;

// gets the path to the jar file if it exists; or the "bin" directory if calling from Eclipse
String jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath()).getAbsolutePath();

// gets the "bin" directory if calling from eclipse or the name of the .jar file alone (without its path)
String jarFileFromSys = System.getProperty("java.class.path").split(";")[0];

// If both are equal that means it is running from an IDE like Eclipse
if (jarFileFromSys.equals(jarDir))
{
    System.out.println("RUNNING FROM IDE!");
    // The path to the jar is the "bin" directory in that case because there is no actual .jar file.
    surroundingJar = jarDir;
}
else
{
    // Combining the path and the name of the .jar file to achieve the final result
    surroundingJar = jarDir + jarFileFromSys.substring(1);
}

System.out.println("JAR File: " + surroundingJar);
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

将“MyClass”替换为类名。

显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。

实际上,这里有一个更好的版本-如果文件夹名中有空格,旧的版本就会失败。

  private String getJarFolder() {
    // get name and path
    String name = getClass().getName().replace('.', '/');
    name = getClass().getResource("/" + name + ".class").toString();
    // remove junk
    name = name.substring(0, name.indexOf(".jar"));
    name = name.substring(name.lastIndexOf(':')-1, name.lastIndexOf('/')+1).replace('%', ' ');
    // remove escape characters
    String s = "";
    for (int k=0; k<name.length(); k++) {
      s += name.charAt(k);
      if (name.charAt(k) == ' ') k += 2;
    }
    // replace '/' with system separator char
    return s.replace('/', File.separatorChar);
  }

至于applet失败的原因,您通常无法访问本地文件。我不太了解JWS,但要处理本地文件,可能无法下载该应用程序。

令人沮丧的是,当您在Eclipse中进行开发时,MyClass.class.getProtectionDomain(). getcodesource (). getlocation()返回/bin目录,这很好,但当您将其编译到jar时,该路径包括/myjarname.jar部分,这为您提供了非法的文件名。

为了让代码既能在ide中工作,又能编译到jar中,我使用了下面这段代码:

URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
    myFile = new File(applicationRootPath, "filename");
}
else{
    myFile = new File(applicationRootPath.getParentFile(), "filename");
}

我有另一种方法来获取类的String位置。

URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();

输出字符串的形式为

C:\Users\Administrator\new Workspace\...

空格和其他字符被处理,并且在没有file:/的形式。这样会更容易使用。