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

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


当前回答

对于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的值)

其他回答

试试这个:

String path = new File("").getAbsolutePath();

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

String path = getClass().getResource("").getPath();

路径总是引用jar文件中的资源。

令人沮丧的是,当您在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");
}

最简单的解决方案是在运行jar时将路径作为参数传递。

你可以用一个shell脚本(Windows中的.bat,其他任何地方的.sh)自动化这个:

java -jar my-jar.jar .

我用过。传递当前工作目录。

更新

您可能希望将jar文件放在子目录中,这样用户就不会意外地单击它。您的代码还应该检查以确保提供了命令行参数,如果缺少参数,则提供良好的错误消息。