private static String getParentDirectoryFromJar(Class aclass) {
String dirtyPath = aclass.getResource("").toString();
String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it
jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath
jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within
if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button.
jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
}
String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8
log.info("get jar path: " + directoryPath);
return directoryPath;
}
获取jar包所在路径
最新推荐文章于 2023-12-21 15:40:05 发布
该代码段是一个Java方法,用于从给定的类(Class)对象中获取JAR文件的父目录路径。首先,它从类的资源路径字符串中移除'file:/', 'jar!'和'%20'等不必要的部分。接着,如果路径不以'.jar'结尾(可能是在Spring Tools Suite中运行),则进一步处理路径。最后,使用Java 8的Paths类获取父目录并返回。
摘要由CSDN通过智能技术生成