java 获取当前执行项目的路径

如何获取当前执行项目的路径?如何获取 java -jar 获取当前jar的绝对路径?

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2021-06-18 10:18:57.298  INFO 87404 --- [           main] c.e.s.SpringbootdemoApplication          : Starting SpringbootdemoApplication on zjMacBook-Pro.local with PID 87404 (/opt/jy/work/ta/springbootdemo/target/classes started by zj in /opt/jy/work/ta/springbootdemo)
2021-06-18 10:18:57.301  INFO 87404 --- [           main] c.e.s.SpringbootdemoApplication          : No active profile set, falling back to default profiles: default
2021-06-18 10:18:58.211  INFO 87404 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

springboot 启动项目能看到如上的日志,可看到已经输出了项目所在路径。

然后mvn clean package 后,使用java -jar 启动,可以看到输出的日志为:

2021-06-18 10:33:38.147  INFO 94484 --- [           main] c.e.s.SpringbootdemoApplication          : Starting SpringbootdemoApplication v0.0.1-SNAPSHOT on zjMacBook-Pro.local with PID 94484 (/opt/jy/work/pa/jarsigned/zjtarget/signed.jar started by zj in /Users/zj) 

日志中已经输出了jar的绝对路径:/opt/jy/work/pa/jarsigned/zjtarget/signed.jar

跟从springboot启动源码,最终找到了获取jar绝对路径的代码,在ApplicationHome.java类中

/**
 * 获取执行代码的绝对路径,获取执行当前jar包的绝对路径
 * @return
 */
String getPath(){
   ApplicationHome applicationHome = new ApplicationHome(SpringbootdemoApplication.class);
   File file = applicationHome.getSource();
   String path = file.getAbsolutePath();
   return path;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值