ID生成工具类
package com.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class IDUtil {
@SuppressWarnings({ "MethodCanBeVariableArityMethod", "Annotation" })
public static void main(String[] args) {
}
public synchronized static String getID() {
return getDate() + getRandomString(IDLENGTH);
}
public synchronized static String getLongID() {
return getDateTime() + getRandomString(IDLENGTH);
}
private final static int IDLENGTH = 10;
private static final char[] S_BASE64CHAR = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
private static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
sb.append(getTime());
return encode(sb.toString().getBytes(), 1, 9);
}
@SuppressWarnings({ "SameParameterValue", "Annotation" })
private static String encode(byte[] data, int off, int len) {
if (len <= 0) {
return "";
}
char out[] = new char[(len / 3) * 4 + 4];
int rindex = off;
int windex = 0;
int rest;
for (rest = len; rest >= 3; rest -= 3) {
int i = ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + (data[rindex + 2] & 0xff);
out[windex++] = S_BASE64CHAR[i >> 18];
out[windex++] = S_BASE64CHAR[i >> 12 & 0x3f];
out[windex++] = S_BASE64CHAR[i >> 6 & 0x3f];
out[windex++] = S_BASE64CHAR[i & 0x3f];
rindex += 3;
}
if (rest == 1) {
int i = data[rindex] & 0xff;
out[windex++] = S_BASE64CHAR[i >> 2];
out[windex++] = S_BASE64CHAR[i << 4 & 0x3f];
out[windex++] = '=';
out[windex++] = '=';
} else if (rest == 2) {
int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff);
out[windex++] = S_BASE64CHAR[i >> 10];
out[windex++] = S_BASE64CHAR[i >> 4 & 0x3f];
out[windex++] = S_BASE64CHAR[i << 2 & 0x3f];
out[windex++] = '=';
}
return new String(out, 0, windex);
}
private static String getDateTime() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
return df.format(new Date());
}
private static String getDate() {
SimpleDateFormat df = new SimpleDateFormat("yyMMdd");
return df.format(new Date());
}
private static String getTime() {
SimpleDateFormat df = new SimpleDateFormat("HHmmss");
return df.format(new Date());
}
}