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

前端 未结 3 796
囚心锁ツ
囚心锁ツ 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:54

    Well, what have worked for me was an adaptation of this answer. The code is:

    if you run using java -jar myapp.jar dirtyPath will be something close to this: jar:file:/D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/BOOT-INF/classes!/br/com/cancastilho/service. Or if you run from Spring Tools Suit, something like this: file:/D:/arquivos/repositorio/myapp/trunk/target/classes/br/com/cancastilho/service

    public String getParentDirectoryFromJar() {
        String dirtyPath = getClass().getResource("").toString();
        String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it
        jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath
        jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within
        if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button. 
            jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
        }
        String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8
        return directoryPath;
    }
    

    EDIT:

    Actually, if your using spring boot, you could just use the ApplicationHome class like this:

    ApplicationHome home = new ApplicationHome(MyMainSpringBootApplication.class);
    home.getDir();    // returns the folder where the jar is. This is what I wanted.
    home.getSource(); // returns the jar absolute path.
    

提交回复
热议问题