Java Random String getRandomString(int size)

Here you can find the source of getRandomString(int size)

Description

get Random String

License

Open Source License

Declaration

public static String getRandomString(int size) 

Method Source Code

//package com.java2s;
/**/*from   w  w w  . j  a  v a  2  s  .c  o m*/
 * <pre>
 *    This program is free software; you can redistribute it and/or modify it under the terms of 
 * the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version. 
 * 
 *    This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details. 
 *    You should have received a copy of the GNU General Public License along with this program; 
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * </pre>
 */

import java.util.Random;

public class Main {
    private final static char[] c = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't',
            'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm',
            'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X',
            'C', 'V', 'B', 'N', 'M' };

    public static String getRandomString(int size) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer(size);
        for (int i = 0; i < size; i++) {
            sb.append(c[Math.abs(random.nextInt()) % c.length]);
        }
        return sb.toString();
    }

    public static String toString(byte[] bytes) {
        if (bytes == null || bytes.length == 0)
            return "";
        StringBuffer buffer = new StringBuffer();
        for (byte byt : bytes) {
            buffer.append((char) byt);
        }
        return buffer.toString();
    }

    public static String toString(Object[] objs) {
        if (objs == null || objs.length == 0)
            return "[]";
        StringBuffer buffer = new StringBuffer("[");
        for (int i = 0; i < objs.length; i++) {
            buffer.append(String.valueOf(objs[i]));
            if (i != objs.length - 1) {
                buffer.append(",");
            }
        }

        buffer.append("]");
        return buffer.toString();
    }
}

Related

  1. getRandomString(int length, String charset)
  2. getRandomString(int min, int max)
  3. getRandomString(int minLength, int maxLength)
  4. getRandomString(int randomPasswordLength)
  5. getRandomString(int size)
  6. getRandomString(int size)
  7. getRandomString(int size)
  8. getRandomString(int size)
  9. getRandomString(int size)