欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-01 14:19:12
...

如何获取当前执行项目的路径?如何获取 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;
}

 

相关标签: java