java随机产生字符串

来源:互联网 发布:java实现自动化发布 编辑:程序博客网 时间:2024/05/01 10:27

 今天在做一个注册模块,要求用到验证码。自己就试着写了一个。

/**
   * 产生随机字符串
   * */
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();
                 }
             }
         }
         char [] randBuffer = new char[length];
         for (int i=0; i<randBuffer.length; i++) {
             randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
         }
         return new String(randBuffer);
}

 

 

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

原创粉丝点击