gpt4 book ai didi

java - 如何动态获取spring boot应用程序jar父文件夹路径?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:34:15 26 4
gpt4 key购买 nike

我有一个使用 java -jar application.jar 运行的 spring boot web 应用程序。我需要从代码中动态获取 jar 父文件夹路径。我怎样才能做到这一点?

我已经试过了this , 但没有成功。

最佳答案

嗯,对我有用的是对 this answer 的改编。 .代码是:

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;
}

编辑:

实际上,如果你使用 spring boot,你可以只使用 ApplicationHome像这样上课:

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.

关于java - 如何动态获取spring boot应用程序jar父文件夹路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com