Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 accomplish that?

I have already tried this, but without success.

like image 323
Carlos Nantes Avatar asked Oct 10 '17 01:10

Carlos Nantes


1 Answers

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.
like image 90
Carlos Nantes Avatar answered Nov 10 '22 08:11

Carlos Nantes