近期有一个 Spring Boot 的项目要整合 Logback,考虑到一些强迫症的原因,想要把日志文件输出到和 jar 包同一目录下,此时需要思考如何获取项目 jar 的运行目录,能拿到项目 jar 的运行目录,Logback 输出文件就没什么大问题了。

解决方案 1:

private static String getResourceBasePath() {
    File path = null;
    try {
        path = new File(ResourceUtils.getURL("classpath:").getPath());
    } catch (FileNotFoundException e) {

    }
    if (path == null || !path.exists()) {
        path = new File("");
    }

    String pathStr = path.getAbsolutePath();
    pathStr = pathStr.replace("\\target\\classes", "");
    return pathStr;
}

Windows 环境下通过 IDEA 运行项目后获取到的目录:F:\项目名称

Linux 环境下通过 jar 运行项目后获取到的目录:/www/wwwroot/项目名称

解决方案 2:

private static String getResourceBasePath() {
    try {
        String path = URLDecoder.decode(Objects.requireNonNull(LogbackContextListener.class.getResource("/")).getPath(), String.valueOf(StandardCharsets.UTF_8));
        if (path.startsWith("file:")) {
            int i = path.indexOf(".jar!");
            path = path.substring(0, i);
            path = path.replaceFirst("file:", "");
        }
        return new File(path).getParentFile().getAbsolutePath();
    } catch(Exception ex) {
        return "";
    }
}

Windows 环境下通过 IDEA 运行项目后获取到的目录:F:\项目名称\target

Linux 环境下通过 jar 运行项目后获取到的目录:/www/wwwroot/项目名称