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

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


当前回答

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

  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,但要处理本地文件,可能无法下载该应用程序。

其他回答

这个方法从存档中的代码中调用,返回.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运行

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

将“MyClass”替换为类名。

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

对于jar文件路径:

String jarPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

获取jar文件的目录路径:

String dirPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
                        .toURI()).getParent();

上面两行的结果是这样的:

/home/user/MyPrograms/myapp/myjar.jar (jarPath的值)

/home/user/MyPrograms/myapp (dirPath的值)

在我最终找到一个有效(且简短)的解决方案之前,我不得不浪费很多时间。 有可能jarLocation带有一个像file:\或jar:file\这样的前缀,可以使用String#substring()来删除。

URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();

这里是其他评论的升级版,在我看来,这些评论的细节并不完整

在.jar文件外使用一个相对的“文件夹”(在jar的相同 位置):

String path = 
  YourMainClassName.class.getProtectionDomain().
  getCodeSource().getLocation().getPath();

path = 
  URLDecoder.decode(
    path, 
    "UTF-8");

BufferedImage img = 
  ImageIO.read(
    new File((
        new File(path).getParentFile().getPath()) +  
        File.separator + 
        "folder" + 
        File.separator + 
        "yourfile.jpg"));