cn.com.sunjiesh.xcutils.common.VersionUtil.java Source code

Java tutorial

Introduction

Here is the source code for cn.com.sunjiesh.xcutils.common.VersionUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.com.sunjiesh.xcutils.common;

import java.util.StringTokenizer;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

/**
 *
 * @author tom
 */
public class VersionUtil {

    /**
     * 
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {

        StringTokenizer version1Tokenizer = new StringTokenizer(version1, ".");
        StringTokenizer version2Tokenizer = new StringTokenizer(version2, ".");
        if (version1.equals(version2)) {
            return 0;
        } else {
            while (version1Tokenizer.hasMoreTokens() && version2Tokenizer.hasMoreTokens()) {
                String version1Token = version1Tokenizer.nextToken();
                String Version2Token = version2Tokenizer.nextToken();
                if (StringUtils.isNotBlank(version1Token)) {
                    version1Token = version1Token.replace("-", "");
                }
                if (StringUtils.isNotBlank(Version2Token)) {
                    Version2Token = Version2Token.replace("-", "");
                }
                if (StringUtils.isNotBlank(version1Token)) {
                    version1Token = version1Token.replace("0", "");
                    if (version1Token.equals("")) {
                        version1Token = "0";
                    }
                }
                if (StringUtils.isNotBlank(Version2Token)) {
                    Version2Token = Version2Token.replace("0", "");
                    if (Version2Token.equals("")) {
                        Version2Token = "0";
                    }
                }
                if (NumberUtils.isDigits(version1Token) && NumberUtils.isDigits(Version2Token)) {//???
                    if (Integer.parseInt(version1Token) < Integer.parseInt(Version2Token)) {
                        return -1;
                    }
                    if (Integer.parseInt(version1Token) > Integer.parseInt(Version2Token)) {
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println("NumberUtils.isNumber(version1)=" + NumberUtils.isNumber("2.3.1"));

        System.out.println("compareVersion=" + compareVersion("1.0", "2.3.1"));
    }
}