Spring Boot 获取项目根路径或者资源文件的路径

在Spring Boot项目中,有时候需要获取项目的根路径,可以通过以下方法获取:

  /**
     * 获取项目根路径
     * 
     * @return
     */
    private static String getResourceBasePath() {
        // 获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            // nothing to do
        }
        if (path == null || !path.exists()) {
            path = new File("");
        }

        String pathStr = path.getAbsolutePath();
        // 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
        pathStr = pathStr.replace("\\target\\classes", "");

        return pathStr;
    }
}

版权声明:本文为weixin_40584261原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。