| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package com.mes.update;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- import java.nio.charset.StandardCharsets;
- /**
- * 本地/远程版本读写与三段数字比较。
- */
- public final class VersionUtil {
- private VersionUtil() {
- }
- /**
- * 读取本地版本:优先安装目录旁 app.version,否则使用配置中的默认版本。
- */
- public static String resolveLocalVersion(File installDir, String configVersion) {
- if (installDir != null) {
- File versionFile = new File(installDir, "app.version");
- String fromFile = readVersionFile(versionFile);
- if (fromFile != null && !fromFile.isEmpty()) {
- return fromFile;
- }
- }
- if (configVersion != null && !configVersion.trim().isEmpty()) {
- return configVersion.trim();
- }
- return "0.0.0";
- }
- public static String readVersionFile(File versionFile) {
- if (versionFile == null || !versionFile.isFile()) {
- return null;
- }
- try (BufferedReader reader = new BufferedReader(
- new InputStreamReader(new FileInputStream(versionFile), StandardCharsets.UTF_8))) {
- String line = reader.readLine();
- if (line == null) {
- return null;
- }
- return line.trim();
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 比较两个版本号。返回 >0 表示 a 更新,<0 表示 b 更新,0 表示相等。
- */
- public static int compare(String a, String b) {
- int[] pa = parse(a);
- int[] pb = parse(b);
- int len = Math.max(pa.length, pb.length);
- for (int i = 0; i < len; i++) {
- int va = i < pa.length ? pa[i] : 0;
- int vb = i < pb.length ? pb[i] : 0;
- if (va != vb) {
- return va - vb;
- }
- }
- return 0;
- }
- public static boolean isNewer(String remote, String local) {
- return compare(remote, local) > 0;
- }
- private static int[] parse(String version) {
- if (version == null || version.trim().isEmpty()) {
- return new int[]{0, 0, 0};
- }
- String cleaned = version.trim();
- if (cleaned.startsWith("v") || cleaned.startsWith("V")) {
- cleaned = cleaned.substring(1);
- }
- String[] parts = cleaned.split("[^0-9]+");
- int[] result = new int[Math.max(3, parts.length)];
- int idx = 0;
- for (String part : parts) {
- if (part == null || part.isEmpty()) {
- continue;
- }
- try {
- result[idx++] = Integer.parseInt(part);
- } catch (NumberFormatException ignored) {
- result[idx++] = 0;
- }
- }
- if (idx == 0) {
- return new int[]{0, 0, 0};
- }
- if (idx < 3) {
- int[] padded = new int[3];
- System.arraycopy(result, 0, padded, 0, idx);
- return padded;
- }
- int[] exact = new int[idx];
- System.arraycopy(result, 0, exact, 0, idx);
- return exact;
- }
- }
|