Wednesday, July 16, 2008

Generate Random Alphanumeric Random String of N Characters with Groovy or Java


I was googling for a Alpha-numeric Random String generation. I come up with two solution. One option is to generate Random Alphanumeric Strings with RandomStringUtils available on Apache Common . The following section of code is borrowed from

import org.apache.commons.lang.RandomStringUtils;
public class RandomStringUtilsTrial {
public static void main(String[] args) {

//Random 8 chars string where letters are enabled while numbers are not.
System.out.print("8 char string using letters but no numbers >>>");
System.out.println(RandomStringUtils.random(8, true, false));


Other Option can be using the Java Uitil class Random as shown below. You don’t have to worry about Apache Common API. The following code section (written for Groovy) generates 100 '32 characters' long Alphanumeric Random string.

private static String validChars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"
private int IDlength=32
int maxIndex = validChars.length()
for(i in 0..99)
{ String resultID = ""
java.util.Random rnd = new java.util.Random(System.currentTimeMillis()*(new java.util.Random().nextInt()))
for ( i in 0..IDlength ) {
int rndPos = Math.abs(rnd.nextInt() % maxIndex);
resultID += validChars.charAt(rndPos)

println resultID

Good luck !


Randy Hudson said...

You can shorten the second snippet quite a bit. Replace everything after the definition of maxIndex by this:

def rnd = new Random()
100.times {
println( (1..IDlength).sum{
validChars[ rnd.nextInt(maxIndex) ]
} )

Bishow Paudel said...

Thanks Randy !

Post a Comment

I love to entertain onymous user Comment !


 © 2006-2010

 ©, Learning from Experiences !