springboot 获取路径

2023-12-13 05:59:44
@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

文章来源:https://blog.csdn.net/mxj588love/article/details/134952245
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。