获取 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;
        }
    }
}

你可能感兴趣的:(获取 Jar 包的路径)