Tuesday, December 18, 2012

Generating Alphanumeric Random Strings

In one of my previous blog post, I had mentioned about the excellent Apache Commons RandomNumberGenerator utility class that is very handy for common use.

Sometimes, we need to generate an alphanumeric ramdom string for specific use cases. For e.g. file names, registry keys, etc. The Apache Commons module has one more class called RandomStringUtils for this.
If you are looking for a more simpler copy-n-paste code, then the following snippet should suffice for most non-secure requirements.

static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rnd = new Random();

String randomString( int len ) 
   StringBuilder sb = new StringBuilder( len );
   for( int i = 0; i < len; i++ ) 
      sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
   return sb.toString();