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

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


当前回答

试试这个:

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

其他回答

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

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

对我来说,在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();
}

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

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”,我注意到它是有效的。

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

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

输出字符串的形式为

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

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

你还可以使用:

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