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

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


当前回答

你还可以使用:

CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();

其他回答

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

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

我试图让罐子运行路径使用

String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();

C:\app>java -jar application.jar

运行名为“application.jar”的jar应用程序,在Windows文件夹“c:\app”中,字符串变量“文件夹”的值是“\c:\app\application.jar”,我在测试路径的正确性时遇到了问题

File test = new File(folder);
if(file.isDirectory() && file.canRead()) { //always false }

所以我试着将“test”定义为:

String fold= new File(folder).getParentFile().getPath()
File test = new File(fold);

以正确的格式获取路径,如“c:\app”而不是“\c:\app\application.jar”,我注意到它是有效的。

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

将“MyClass”替换为类名。

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

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

我用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上进行测试