前言
封装一个获取当前jar包所在路径的方法、用于存取jar包相同目录下文件获取绝对路径,兼容win、linux、macos
一、上代码(方法可直接复制)
/**
* 文件处理工具类
*
* @author jjh
*/
@Slf4j
public class FileUtils
{
/**
* 比如jar包路径为 D:/project/admin.jar
* 则方法返回 D:/project/
*
* 获取jar包绝对路径 兼容win、linux、macos
* @return
*/
public static String getPath()
{
String path = FileUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
log.info("原始路径:{}", path);
if(System.getProperty("os.name").contains("dows"))
{
//path -> file:/D:/Haier/hlmcheckup-admin.jar!/BOOT-INF/lib/hlmcheckup-common-1.0.0.jar!/
//如果是windows系统,前面有可能有“file:”要替换掉。
path = path.replace("file:", "");
path = path.substring(1,path.length());
log.info("win系统:{}", path);
}
if(path.contains("jar"))
{
//这里根据你jar包名称分割
//D:/Haier/hlmcheckup-admin.jar!/BOOT-INF/lib/hlmcheckup-common-1.0.0.jar!/
// -> D:/Haier/
String[] split = path.split("hlmcheckup-admin.jar");
log.info("jar包路径:{}", split[0]);
return split[0];
}
//"hlmcheckup-common/target/classes/" 为当前类路径 linux与macos需要替换掉
return path.replace("hlmcheckup-common/target/classes/", "");
}
}
二、使用
public static void main(String[] args) {
//getPath()为上文中封装的静态方法,注意要修改方法中的jar包名字与类路径
String jarPath = FileUtils.getPath();
System.out.println(jarPath);
//D:/Haier/
}
总结
注意要修改方法中的jar包名字与类路径
补充
2024-04-15更新,一种更简便的方式
System.getProperty("user.dir") + "/".replace("file:/", "/");