用Java比较JRE版本
很多程序采用了较高版本的JDk开发,这些程序可能使用了一下高
版本 JDK的 特 性,在低版本的JDK上无法运行或者无法显示出足够好
的效果,所 以在程序运 行之前 需要判断当前系统中的JRE版本,下
面给出一个版本判断的类。
VersionChecker.java
import java.util.StringTokenizer;
public class VersionChecker
{
public void check(String desiredVersion)
{
String currentVersion = System.getProperty(“java.version“);
boolean isOk;
try
{
isOk = versionCompare(currentVersion,
desiredVersion) >= 0;//如果当前版本高于需求版本,可以执行
}
catch (NumberFormatException exception)
{
isOk = false;
}
if (isOk)
{
//do what you want
System.out.println(“Current JRE version is OK!“);
}
else
{
System.out.println(“The current JRE version is not match!“);
}
}
public static int versionCompare(String v1,
String v2)
{
StringTokenizer t1 = new StringTokenizer(v1, “._“);
StringTokenizer t2 = new StringTokenizer(v2, “._“);
while (t1.hasMoreTokens())
{
if (!t2.hasMoreTokens()) return 1;
int n1 = Integer.parseInt(t1.nextToken());
int n2 = Integer.parseInt(t2.nextToken());
int d = n1 – n2;
if (d != 0) return d;
}
return t2.hasMoreTokens() ? –1 : 0;
}
public static void main(String args[]){
VersionChecker vc = new VersionChecker();
vc.check(“1.4.0“);
}
}
public class VersionChecker
{
public void check(String desiredVersion)
{
String currentVersion = System.getProperty(“java.version“);
boolean isOk;
try
{
isOk = versionCompare(currentVersion,
desiredVersion) >= 0;//如果当前版本高于需求版本,可以执行
}
catch (NumberFormatException exception)
{
isOk = false;
}
if (isOk)
{
//do what you want
System.out.println(“Current JRE version is OK!“);
}
else
{
System.out.println(“The current JRE version is not match!“);
}
}
public static int versionCompare(String v1,
String v2)
{
StringTokenizer t1 = new StringTokenizer(v1, “._“);
StringTokenizer t2 = new StringTokenizer(v2, “._“);
while (t1.hasMoreTokens())
{
if (!t2.hasMoreTokens()) return 1;
int n1 = Integer.parseInt(t1.nextToken());
int n2 = Integer.parseInt(t2.nextToken());
int d = n1 – n2;
if (d != 0) return d;
}
return t2.hasMoreTokens() ? –1 : 0;
}
public static void main(String args[]){
VersionChecker vc = new VersionChecker();
vc.check(“1.4.0“);
}
}
版权声明:本文为BlueMagic原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。