最近应工程的需要写了个简单的UUID类。
可通过方法 String getUUID(int length) 使用。length是制定返回字符串的长度。
一般最好能20位以上
package test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class UUIDGenerator {
private static String baseUUID = null;
private static long incrementingValue = 0;
private static Random myRand = null;
public static String getUUID(int length) {
if (baseUUID == null) {
getInitialUUID(length);
}
long i = ++incrementingValue;
if (i >= Long.MAX_VALUE || i < 0) {
incrementingValue = 0;
i = 0;
}
return baseUUID;
}
protected static synchronized void getInitialUUID(int length) {
if (baseUUID != null) {
return;
}
if (myRand == null) {
myRand = new Random();
}
long rand = myRand.nextLong();
String sid;
try {
sid = InetAddress.getLocalHost().toString();
} catch (UnknownHostException e) {
sid = Thread.currentThread().getName();
}
StringBuffer sb = new StringBuffer();
sb.append(sid);
sb.append(":");
sb.append(Long.toString(rand));
sb.append(System.currentTimeMillis());
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
}
md5.update(sb.toString().getBytes());
byte[] array = md5.digest();
StringBuffer sb2 = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
sb2.append(Integer.toHexString(b));
}
int begin = 0;
baseUUID = sb2.toString().substring(begin, length).toUpperCase();
}
public static void main(String[] args) {
System.out.println(UUIDGenerator.getUUID(10));
}
}