How to generate a random String in Java [duplicate]
Generating a random string of characters is easy - just use java.util.Random
and a string containing all the characters you want to be available, e.g.
public static String generateString(Random rng, String characters, int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.
This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7)
.
There are 10^7 equiprobable (if java.util.Random
is not broken) distinct values so uniqueness may be a concern.
You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.
java.util.UUID.randomUUID().toString()
http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html