How to get spring boot application jar parent folder path dynamically?

前端 未结 3 809
囚心锁ツ
囚心锁ツ 2021-02-20 06:16

I have a spring boot web application which I run using java -jar application.jar. I need to get the jar parent folder path dynamically from the code. How can I

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 06:58

    Try this code

    public static String getParentRealPath(URI uri) throws URISyntaxException {
        if (!"jar".equals(uri.getScheme()))
            return new File(uri).getParent();
        do {
            uri = new URI(uri.getSchemeSpecificPart());
        } while ("jar".equals(uri.getScheme()));
        File file = new File(uri);
        do {
            while (!file.getName().endsWith(".jar!"))
                file = file.getParentFile();
            String path = file.toURI().toString();
            uri = new URI(path.substring(0, path.length() - 1));
            file = new File(uri);
        } while (!file.exists());
        return file.getParent();
    }
    
    URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI();
    System.out.println(getParentRealPath(uri));
    

提交回复
热议问题