有没有办法在Java中生成8个字符长的随机且唯一的字符串?
String id = getRandomString();
然后id
将会是例如wf41Av5g
import org.apache.commons.lang.RandomStringUtils;
public class RandomStringUtilsTrial {
public static void main(String[] args) {
System.out.print("8 char string >>>");
System.out.println(RandomStringUtils.random(8, true, true));
}
}
唯一性属性取决于您使用它的范围。Java当然可以生成随机字符串,但如果您想要一个通用唯一标识符,则可以使用UUID
类。
String unique = UUID.randomUUID().toString();
String eightChars = unique.substring(28);
。 - Johan Sjöberg您可以根据当前时间创建这个字符串。
例如:
2014 06 04 16 21 20 79 ---> 14 06 04 16 21 20 79
然后,您可以使用表格(http://en.wikipedia.org/wiki/Base64 - 请注意,所有的数字都小于59)将除最后两位以外的每两个数字翻译成一个字母数字字符。
然后你会得到:
14 - O
06 - G
04 - E
16 - Q
21 - V
20 - U
OGEQVU79 <- 正好8个字符。有点复杂,但如果您不经常调用函数,这种方法是有效的(间隔时间大于0.01秒)。
public String getRandomString(int length, char[] characterSet) {
StringBuilder sb = new StringBuilder();
for (int loop = 0; loop < length; loop++) {
int index = new Random().nextInt(characterSet.length);
sb.append(characterSet[index]);
}
String nonce = sb.toString();
return nonce;
}
char[] chars = new char[]{ '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',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
Random rnd = new Random();
int charsLength = chars.length;
int passLength = 8;
StringBuilder password = new StringBuilder();
for (int i = 0; i < passLength; i++)
{
int index = rnd.nextInt(charsLength - i - 1);
// Simple swap
char a = chars[i + index];
chars[i + index] = chars[i];
chars[i] = a;
password.append(a);
}
System.out.print(password);
ifJjuYrR
NpY3TfIU
LGFm8Ng9
sV4Gctb7
4fyhlSuQ
使用java.util.UUID的快速而简单的解决方案:
public String getRandomString(int length) {
return UUID.randomUUID().toString().subSequence(0, length);
}
private String uniqid() {
Random random = new Random();
String tag = Long.toString(Math.abs(random.nextLong()), 36);
return tag.substring(0, 8);
}
我知道这是一个旧帖子,但这可能对某些人有所帮助。
对于我来说,这个方法有效:
System.out.println(UniqueIdGenerator.fromBase10(System.currentTimeMillis()));
在同一个JVM上的每个毫秒都应该是唯一的。
使用:
public class UniqueIdGenerator {
private static final String MIX_STRING = "abcdefghijklmnopqrstuvwxyz1234567890";
private static final int MIX_STRING_LENGTH = MIX_STRING.length();
public static String fromBase10(final long base10) {
if (base10 == 0)
return "0";
long temp = base10;
final StringBuilder sb = new StringBuilder();
while (temp > 0) {
temp = fromBase10(temp, sb);
}
return sb.reverse().toString();
}
private static Long fromBase10(final long base10, final StringBuilder sb) {
final int rem = (int) (base10 % MIX_STRING_LENGTH);
sb.append(MIX_STRING.charAt(rem));
return base10 / MIX_STRING_LENGTH;
}
}
你也可以改变 MIX_STRING
中的字符顺序,甚至添加大写字母或符号。