Possible Duplicate:
How to generate a random String in Java
我想在不使用 apache 类的情况下生成 20 个字符的随机字符串。我真的不在乎是否是字母数字。另外,我稍后会将其转换为字节数组。
谢谢,
最佳答案
给你。只需在第一行指定要允许的字符即可。
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
关于java - 如何生成20个字符的随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683327/