1.6 如何获取正在运行的JAR文件的路径?| Java Debug 笔记

637 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>

提问:如何获取正在运行的JAR文件的路径?

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

因此,如果foo.jar在中C:\FOO\,无论我当前的工作目录是什么,我都希望获取该路径。

回答1:

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

将“MyClass”替换为你自己的类,toURI()对于避免特殊字符(包括空格和加号)出现问题至关重要。

回答2:

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

这种解决方法可以解决空格和特殊字符的问题。

还有一点需要注意:从Jar调用此函数时,jar的名称会附加在我最后返回的字符串的后面,因此必须执行:

path.substring(0, path.lastIndexOf("/") + 1);

回答3:Paths类

public final class Paths {
    private Paths() {
    }

    public static Path get(String first, String... more) {
        return Path.of(first, more);
    }

    public static Path get(URI uri) {
        return Path.of(uri);
    }
}

我们再看看Path类的of方法到底是啥

static Path of(URI uri) {
        String scheme = uri.getScheme();
        if (scheme == null) {
            throw new IllegalArgumentException("Missing scheme");
        } else if (scheme.equalsIgnoreCase("file")) {
            return FileSystems.getDefault().provider().getPath(uri);
        } else {
            Iterator var2 = FileSystemProvider.installedProviders().iterator();

            FileSystemProvider provider;
            do {
                if (!var2.hasNext()) {
                    throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed");
                }

                provider = (FileSystemProvider)var2.next();
            } while(!provider.getScheme().equalsIgnoreCase(scheme));

            return provider.getPath(uri);
        }
    }

最终实现:

Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());

文章翻译自Stack Overflow :stackoverflow.com/questions/3…