java application文件夹_如何动态获取Spring Boot Application Jar的父文件夹路径?

小编典典

嗯,对我有用的是对该答案的改编。代码是:

如果使用java -jar myapp.jar进行运行,dirtyPath将接近以下内容:jar:file:/

D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/ BOOT-

INF / classes!/ br / com / cancastilho / service。或者,如果您从Spring Tools

Suit运行,则如下所示: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.

2020-05-30

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值