java随机产生字符串

9年前

/**
   * 产生随机字符串
   * */
private static Random randGen = null;
private static char[] numbersAndLetters = null;
private static Object initLock = new Object();


public static final String randomString(int length) {

         if (length < 1) {
             return null;
         }
         if (randGen == null) {
             synchronized (initLock) {
                 if (randGen == null) {
                     randGen = new Random();
                     numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
                     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                     //numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                 }
             }
         }
         char [] randBuffer = new char[length];
         for (int i=0; i<randBuffer.length; i++) {
             randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
          //randBuffer[i] = numbersAndLetters[randGen.nextInt(35)];
         }
         return new String(randBuffer);
}

调用此方法randomString(int),int是字符串的长度,即可产生指定长度的随机字符串。

原文出处:http://hi.baidu.com/samuel_vong/blog/item/95471f7e2cdab33d0cd7dad1.html