获取 Jar 包的路径

package com.lechisoft.ms.utils;


import java.io.File;

public class PathUtil {
    /**
     * 获取obj所在Jar包的物理路径
     *
     * @param obj 任意对象
     * @return 对象所在Jar包的物理路径
     */
    public static String getJarPath(Object obj) {
        String path = obj.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("PathUtil->getJarPath:" + path);
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length());
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            path = path.substring(0, path.lastIndexOf(File.separator));
        }
        path = path.replace(File.separator + "target" + File.separator + "classes" + File.separator, "");
        path = (path.endsWith("/") || path.endsWith("\\")) ? path.substring(0, path.length() - 1) : path;
        path = path.replace("file:", "");
        System.out.println("PathUtil->getJarPath:" + path);
        return path;
    }

    /**
     * 获取相对于obj所在Jar包的路径的物理路径
     *
     * @param path classpath:或file:
     * @param obj  任意对象
     * @return 相对于obj所在Jar包的路径的物理路径
     */
    public static String getFilePath(String path, Object obj) {
        path = path.trim();
        if (path.startsWith("file:")) {
            path = path.replace("file:", "");
            path = path.startsWith("." + File.separator) ? path.replace("." + File.separator, "") : path;
            path = path.startsWith(File.separator) ? path.replace(File.separator, "") : path;
            path = path.replace("/", File.separator);
            path = path.replace("\\", File.separator);
            return PathUtil.getJarPath(obj) + File.separator + path;
        } else {
            path = path.replace("classpath:", "");
            path = obj.getClass().getClassLoader().getResource(path).toString();
            path = path.replace("file:", "");
            return path;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容