1、java怎么随机生成24字节Byte Array(不能有重复)
2、然后Array通过base64编码获得32字节字符串
------解决方案--------------------
public static void main(String[] args) {
byte[] bytes = getRandomByteArray(24);
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(bytes));
}
public static byte[] getRandomByteArray(int len) {
if (len < 0
------解决方案--------------------
len > 256) {
throw new IllegalArgumentException("Illegal length: " + len);
}
byte[] bytes = new byte[256];
for (int i = 0; i < 256; i++) {
bytes[i] = (byte)i;
}
Random rand = new Random();
byte[] randBytes = new byte[len];
int size = 256;
while (--len >= 0) {
int index = rand.nextInt(size);
randBytes[len] = bytes[index];
bytes[index] = bytes[--size];
}
return randBytes;
}
------解决方案--------------------
import java.util.concurrent.atomic.AtomicLong;
import org.apache.catalina.util.Base64;
public class Random {
private static final AtomicLong sequence = new AtomicLong();
private static void convert(long data, byte[] buffer, int offset){
buffer[offset+0] = (byte)((data>>>56)&0xFF);
buffer[offset+1] = (byte)((data>>>48)&0xFF);
buffer[offset+2] = (byte)((data>>>40)&0xFF);
buffer[offset+3] = (byte)((data>>>32)&0xFF);
buffer[offset+4] = (byte)((data>>>24)&0xFF);
buffer[offset+5] = (byte)((data>>>16)&0xFF);
buffer[offset+6] = (byte)((data>>> 8)&0xFF);
buffer[offset+7] = (byte)((data>>> 0)&0xFF);
}
//该方法在多线程编程中要注意用法(单例),否则会产生重复数据。
public String next(){
long[] rands = new long[3];
rands[1] = System.currentTimeMillis();
java.util.Random jRand = new java.util.Random(rands[1]);
rands[0] = jRand.nextLong();
rands[2] = sequence.incrementAndGet();
byte[] data = new byte[24];
convert(rands[0], data, 0);
convert(rands[1], data, 8);
convert(rands[2], data, 16);
return Base64.encode(data);
}
public static void main(String[] args) {
Random rand = new Random();
System.out.println(rand.next());
System.out.println(rand.next());
}
}
------解决方案--------------------
难道我理解错了?你的意思是像我代码保证的数组24个字节各不相同,
还是你生成的1000W个数组之间各不相同?