java:版本号比较(compare version string)

Posted 10km

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java:版本号比较(compare version string)相关的知识,希望对你有一定的参考价值。

java中如何实现两个版本号j(如5.7 vs 5.7.36)怎么比较大小?

百度上用java 比较版本号关键字搜索了一下都找到的文章都要自己写代码做字符串分割,分段比较。。。好麻烦。
bing/google上搜索英文关键字java compare version,第二个就是这篇在stackoverflow上的文章
https://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java
给出了最简单的现成的方案:使用org.apache.maven:maven-artifact:3.2.5库中的
org.apache.maven.artifact.versioning.DefaultArtifactVersion,比较版本号就变得很简单:

import org.apache.maven.artifact.versioning.DefaultArtifactVersion;

DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1");
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10");

DefaultArtifactVersion version = new DefaultArtifactVersion("1.11");

if (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) 
    System.out.println("Sorry, your version is unsupported");

下面是我基于org.apache.maven.artifact.versioning.DefaultArtifactVersion实现的用于JDBC检查数据库类型和版本号的方法:

import static com.google.common.base.Preconditions.checkState;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
/**
 * JDBC工具类
 * @author guyadong
 *
 */
public class JDBCUtility 
	/**
	 * 检查数据库类型及版本是否满足要求,不满足则抛出异常
	 * @param metaData
	 * @param requiredProductName 要求的数据库名,such as 'mysql'
	 * @param requiredMinVersion     要求的数据最低版本号,such as '5.7.36'
	 * @param requiredMaxVersion    要求的数据最高版本号,为@code null或空忽略
	 * @throws SQLException  从DatabaseMetaData读取数据异常
	 */
	public static void checkDatatbaseVersion(DatabaseMetaData metaData,String requiredProductName,String requiredMinVersion,String requiredMaxVersion) throws SQLException
		String productName = checkNotNull(metaData,"metaData is null").getDatabaseProductName();
		DefaultArtifactVersion minVersion = new DefaultArtifactVersion(checkNotNull(requiredMinVersion,"requiredMinVersion is null"));
		DefaultArtifactVersion version = new DefaultArtifactVersion(metaData.getDatabaseProductVersion());
		checkState(productName.equals(requiredProductName),"%s required",requiredMinVersion);
		checkState(version.compareTo(minVersion) >= 0,"Sorry, %s min version %s is required",requiredProductName,minVersion);
		if(!Strings.isNullOrEmpty(requiredMaxVersion))
			DefaultArtifactVersion maxVersion = new DefaultArtifactVersion(requiredMaxVersion);
			checkState(version.compareTo(maxVersion) <= 0,"Sorry, %s max version %s is required",requiredProductName,maxVersion);
		
	

调用示例:

import java.sql.Connection;
// 创建数据库连接
Connection con=........;
JDBCUtility.checkDatatbaseVersion(con.getMetaData(),"MySQL","5.7",null);

参考资料

《How do you compare two version Strings in Java?》

以上是关于java:版本号比较(compare version string)的主要内容,如果未能解决你的问题,请参考以下文章

165 Compare Version Numbers 比较版本号

LeetCode 165 Compare Version Numbers(比较版本号)(string)(*)

165. Compare Version Numbers比较版本号的大小

165. Compare Version Numbers - LeetCode

165. Compare Version Numbers

软件版本号比较(字符串比较)