Get a random string with the request length - Java java.lang

Java examples for java.lang:String Random

Description

Get a random string with the request length

Demo Code

import java.util.Random;

public class Main {

  public static void main(String[] argv) {
    int len = 42;
    System.out.println(getRandomString(len));
  }// www.  ja v a2  s  .c om

  private static final String[] RANDOM_CHARSET = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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" };

  /**
   * Get a random string with the request length
   * 
   * @param length
   *          of the random string
   * 
   * @returns a random string
   */
  public static String getRandomString(int len) {
    Random rand = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < len; i++) {
      sb = sb.append(RANDOM_CHARSET[rand.nextInt(RANDOM_CHARSET.length)]);
    }
    return sb.toString();
  }

}

Related Tutorials