我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
您可以为此使用Apache Commons库RandomStringUtils:
RandomStringUtils.randomAlphanumeric(20).toUpperCase();
其他回答
在一行中:
Long.toHexString(Double.doubleToLongBits(Math.random()));
来源:Java-生成随机字符串
使用Apache Commons库,可以在一行中完成:
import org.apache.commons.lang.RandomStringUtils;
RandomStringUtils.randomAlphanumeric(64);
文档
Java提供了一种直接实现这一点的方法。如果你不想要破折号,它们很容易去掉。只需使用uuid.replace(“-”,“”)
import java.util.UUID;
public class randomStringGenerator {
public static void main(String[] args) {
System.out.println(generateString());
}
public static String generateString() {
String uuid = UUID.randomUUID().toString();
return "uuid = " + uuid;
}
}
输出
uuid = 2d7428a6-b58c-4008-8575-f05549f16316
您可以使用UUID类及其getLeastSignificantBits()消息来获取64位随机数据,然后将其转换为基数36的数字(即由0-9、a-Z组成的字符串):
Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
这将产生一个长达13个字符的字符串。我们使用Math.abs()来确保没有负号潜入。
public static String getRandomString(int length) {
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String randomStr = sb.toString();
return randomStr;
}