軟件版本號比較 java工具類
阿新 • • 發佈:2019-03-13
out turn 軟件版本 最小 system rip replace port pan
這段程序主要用於比較sdk的版本號,例如 8.9.1 和8.9.0,8.9.1和8.7的比較。
import org.apache.commons.lang3.StringUtils; import java.util.regex.Pattern; public class NumUtils { /** * @description 比較SDK版本號 * @param version1 * @param version2 * @return */ public static int compareVersion(String version1, String version2){if (version1 == null || version2 == null) { } version1 = version1.replaceAll("([^(\\d|\\.)])", ""); version2 = version2.replaceAll("([^(\\d|\\.)])", ""); String[] versionArray1 = version1.split("\\.");//註意此處為正則匹配, 不能用.; String[] versionArray2 = version2.split("\\.");int idx = 0; int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小長度值 int diff = 0; while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比較長度 && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比較字符 ++idx; } //如果已經分出大小,則直接返回,如果未分出大小,則再比較位數,有子版本的為大; diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length; return diff; } public static void main(String[] args) {
System.out.println(compareVersion("6.0.0".replaceAll("([^(\\d|\\.)])", ""), "6.0.0") ==0); //true
System.out.println(compareVersion("5.6.1".replaceAll("([^(\\d|\\.)])", ""), "5.6.0") > 0); //true
System.out.println(compareVersion("5.6.1".replaceAll("([^(\\d|\\.)])", ""), "5.6.2") > 0); //false
} }
軟件版本號比較 java工具類