springboot 获取路径

java 复制代码
@PostConstruct
    public void setup() {

        try {

            // jar包所在目录  /Users/mashanshan

            String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
            System.out.println("path:" + path);  // file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

            ApplicationHome home = new ApplicationHome(getClass());
            File jarFile1 = home.getSource();
            String path0 = jarFile1.getParentFile().toString();
            System.out.println("path0: " + path0);  // /Users/mashanshan

            String path1 = ManualController.class.getClassLoader().getResource("").getPath();
            System.out.println("path1: " + path1);  // file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

            String path2 = System.getProperty("user.dir");
            System.out.println("path2:" + path2);  // /Users/mashanshan

            File path3 = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println("path3:" + path3.getAbsolutePath());  // /Users/mashanshan/file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!

            File path4 = new File("");
            System.out.println("path4:" + path4.getAbsolutePath());  ///Users/mashanshan

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

开发环境运行输出:

path:/Users/mashanshan/gitresp/manual-server/manual-admin/target/classes/

path0: /Users/mashanshan/gitresp/manual-server/manual-admin/target

path1: /Users/mashanshan/gitresp/manual-server/manual-admin/target/classes/

path2:/Users/mashanshan/gitresp/manual-server

path3:/Users/mashanshan/gitresp/manual-server/manual-admin/target/classes

path4:/Users/mashanshan/gitresp/manual-server

直接运行jar包输出:

path:file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

path0: /Users/mashanshan

path1: file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

path2:/Users/mashanshan

path3:/Users/mashanshan/file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!

path4:/Users/mashanshan

相关推荐
草字12 分钟前
uniapp 如果进入页面输入框自动聚焦,此时快速返回页面或者跳转到下一个页面,输入法顶上来的页面出现半屏的黑屏问题。
java·前端·uni-app
博主逸尘19 分钟前
uniApp实战六:Echart图表集成
java·uni-app·php
橙子家25 分钟前
Bcrypt 简介与加密和验证示例【加密知多少系列_8】
后端
无限大61 小时前
《计算机“十万个为什么”》之 🔠 字符集:数字世界的文字密码本 🗝️
后端
星月昭铭1 小时前
Spring AI集成Elasticsearch向量检索时filter过滤失效问题排查与解决方案
人工智能·spring boot·spring·elasticsearch·ai
陈煜的博客1 小时前
elasticSearch 增删改查 java api
java·大数据·elasticsearch
hweiyu001 小时前
Scala实用编程(附电子书资料)
开发语言·后端·scala
桦说编程2 小时前
交替打印最容易理解的实现——同步队列
java·后端·设计模式
土族程序员2 小时前
JavaFX CSS @font-face 错误全面分析 loadStylesheetUnPrivileged / reportException
java·css·javafx
猿小蔡-Cool2 小时前
Android Studio Memory Monitor内存分析核心指标详解
android·java·jvm