一、背景
我們經常會遇到比較兩個jar包的版本號,這里貼下相關實現。
請尊重作者勞動成果,轉載請標明原文鏈接:https://www.cnblogs.com/waterystone/p/11385472.html
二、方案
2.1 引用maven-artifact
<dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-artifact</artifactId> <version>3.6.0</version> </dependency>
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
public void compareTo() {
DefaultArtifactVersion version1 = new DefaultArtifactVersion("1.1.14");
DefaultArtifactVersion version2 = new DefaultArtifactVersion("1.2.7");
int res = version1.compareTo(version2);
logger.info("res={}", res);
}
2.2 自己實現
源碼參考:https://github.com/waterystone/adu-test/blob/master/src/main/java/com/adu/utils/VersionUtil.java
package com.adu.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* jar包中版本相關的工具。
* @author adu
* @date 2019-08-20 17:27
*/
public class VersionUtil {
private static final Logger logger = LoggerFactory.getLogger(VersionUtil.class);
/**
* @param jarName1 要求jar名稱必須是*-x.y.z(.|-)*的形式,x、y、z代表任意數字,且可以有多個。如abc-1.jar、abc-1.2.jar、abc-1.2.3.jar、abc-1.2.3.4.jar、abc-1.2.3-jre.jar.
* @param jarName2 要求jar名稱必須是*-x.y.z(.|-)*的形式,x、y、z代表任意數字,且可以有多個。如abc-1.jar、abc-1.2.jar、abc-1.2.3.jar、abc-1.2.3.4.jar、abc-1.2.3-jre.jar.
* @return 0:相等;1:大於;-1:小於。
*/
public static int compareVersion(String jarName1, String jarName2) {
int res = 0;
String version1 = extractVersion(jarName1);
String version2 = extractVersion(jarName2);
String[] levels1 = version1.split("\\.");
String[] levels2 = version2.split("\\.");
int length = Math.max(levels1.length, levels2.length);
for (int i = 0; i < length; i++) {
Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
int compare = v1.compareTo(v2);
if (compare != 0) {
res = compare;
break;
}
}
logger.debug("op=end_compareVersion,jarName1={},jarName2={},version1={},version2={},res={}", jarName1, jarName2, version1, version2, res);
return 0;
}
//要求jar名稱必須是*-x.y.z(.|-)*的形式,x、y、z代表任意數字,且可以有多個。如abc-1.jar、abc-1.2.jar、abc-1.2.3.jar、abc-1.2.3.4.jar、abc-1.2.3-jre.jar.
private static final String VERSION_REGEX = "-((\\d+.)+\\d)(\\.|-)";
private static Pattern VERSION_PATTERN = Pattern.compile(VERSION_REGEX);
/**
* 抽取出jar包名稱中的version
*
* @param jarName 要求jar名稱必須是*-x.y.z(.|-)*的形式,x、y、z代表任意數字,且可以有多個。如abc-1.jar、abc-1.2.jar、abc-1.2.3.jar、abc-1.2.3.4.jar、abc-1.2.3-jre.jar.
* @return
*/
public static String extractVersion(String jarName) {
Matcher matcher = VERSION_PATTERN.matcher(jarName);
if (matcher.find()) {
return matcher.group(1);
}
logger.error("[ERROR_extractVersion_illegal_param]fullJarName={}", jarName);
throw new IllegalArgumentException(String.format("非法參數[%s],無法提取版本,請檢查!", jarName));
}
}
