Java Random String getRandomString(int length, String charset)

Here you can find the source of getRandomString(int length, String charset)

Description

Generate a random string using current time and charset

License

Open Source License

Parameter

Parameter Description
length of the random string to generate
charset use to generate random value

Return

random string, empty if charset is null or length <= 0

Declaration

public static String getRandomString(int length, String charset) 

Method Source Code


//package com.java2s;
/*//from w  w w. ja  v a 2 s.c  o  m
 * Cerberus  Copyright (C) 2013  vertigo17
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of Cerberus.
 *
 * Cerberus 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.
 *
 * Cerberus 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 Cerberus.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Random;

public class Main {
    /**
     * Generate a random string using current time and charset
     *
     * @param length of the random string to generate
     * @param charset use to generate random value
     * @return random string, empty if charset is null or length <= 0
     */
    public static String getRandomString(int length, String charset) {
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();

        if (charset == null) {
            return sb.toString();
        }

        for (int i = 0; i < length; i++) {
            int pos = rand.nextInt(charset.length());
            sb.append(charset.charAt(pos));
        }

        return sb.toString();
    }
}

Related

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