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

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


当前回答

对我来说最好的解决方案:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

这应该可以解决空格和特殊字符的问题。

其他回答

我很惊讶地发现,最近没有人建议使用Path。以下是引用:“Path类包括各种方法,可用于获取路径信息、访问路径元素、将路径转换为其他形式或提取路径的部分”

因此,一个好的替代方法是获取Path对象为:

Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
String path = getClass().getResource("").getPath();

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

如果你从Gnome桌面环境(不是任何脚本或终端)点击运行jar,上面所选的答案是不工作的。

相反,我认为下面的解决方案在任何地方都适用:

    try {
        return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return "";
    }

使用ClassLoader.getResource()来查找当前类的URL。

例如:

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

(这个例子来自一个类似的问题。)

要找到该目录,需要手动分解URL。有关jar URL的格式,请参阅JarClassLoader教程。

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

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