Java Random String generateRandomString(int length, String charset)

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

Description

Generate a random n-length alphanumeric string.

License

Open Source License

Parameter

Parameter Description
length The length of the string to generate.
charset The charset to use.

Return

The randomly generated String.

Declaration

public static String generateRandomString(int length, String charset) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w.  ja  v a  2 s .c o m*/
 * This file is part of SpaceRTK (http://spacebukkit.xereo.net/).
 *
 * SpaceRTK is free software: you can redistribute it and/or modify it under the terms of the
 * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative
 * Common organization, either version 3.0 of the license, or (at your option) any later version.
 *
 * SpaceRTK 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
 * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license for more details.
 *
 * You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA)
 * license along with this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * Generate a random n-length alphanumeric string.
     * @param length The length of the string to generate.
     * @param charset The charset to use.
     * @return The randomly generated String.
     */
    public static String generateRandomString(int length, String charset) {
        String str;
        try {
            str = new String(new byte[] {}, charset);
        } catch (UnsupportedEncodingException ex) {
            System.err.println("ERROR: Unsupported encoding: " + charset);
            ex.printStackTrace();
            return null;
        }

        for (int i = 0; i < length; i++) {
            int rand = (int) (Math.random() * 62);
            if (rand > 9 && rand < 36) {
                rand += 7;
            } else if (rand > 35) {
                rand += 13;
            }
            str += (char) (rand + 48);
        }
        return str;
    }
}

Related

  1. generateRandomString(int length)
  2. generateRandomString(int length)
  3. generateRandomString(int length)
  4. generateRandomString(int length)
  5. generateRandomString(int Length, String caseType)
  6. generateRandomString(int minLength, int maxLength, int minLCaseCount, int minUCaseCount, int minNumCount, int minSpecialCount)
  7. generateRandomString(int n)
  8. generateRandomString(int n)
  9. generateRandomString(int size)