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;
}
上一篇: spring-boot异步线程池
下一篇: Spring boot异步任务