如何动态获取Spring Boot Application Jar的父文件夹路径? [英] How to get spring boot application jar parent folder path dynamically?
问题描述
我有一个Spring Boot Web应用程序,该应用程序是使用 java -jar application.jar 运行的.我需要从代码动态获取jar父文件夹路径.我该怎么办?
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.
推荐答案
好,对我有用的是对此答案. 代码是:
Well, what have worked for me was an adaptation of this answer. The code is:
如果使用java -jar myapp.jar进行运行,dirtyPath将很接近 到此:jar:文件:/D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/BOOT-INF/classes!/br/com/cancastilho/service. 或者,如果您从Spring Tools Suit运行,则如下所示: 文件:/D:/arquivos/repositorio/myapp/trunk/target/classes/br/com/cancastilho/service
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;
}
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.
这篇关于如何动态获取Spring Boot Application Jar的父文件夹路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!