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 包的路径
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 通过class.getResource()方法在IDEA中运行的路径和生成jar包获取的的路径是不同的。在中国象棋...
- 这两天需要在服务器端放一个水印图片,然后读取这个水印给图片添加水印。如何添加水印的方法网上也有一些,这里提两个类来...
- 问题场景:Demo工程引入a.jar,b.jar两个jar包,a.jar和b.jar下都存在同一个db.prope...