Java Random String getRandomString(int len)

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

Description

get Random String

License

Apache License

Declaration

public static String getRandomString(int len) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Random;

public class Main {
    public static final int RANDOM_TYPE_NORMAL = 1;
    public static final int RANDOM_TYPE_ALNUM = 2;
    public static final int RANDOM_TYPE_ALPHA = 3;

    public static String getRandomString(int len) {
        return getRandomString(len, RANDOM_TYPE_NORMAL);
    }//from  w  w w  .jav a 2  s . c o  m

    public static String getRandomString(int len, int randomType) {
        if (len < 1) {
            return "";
        }

        String str;

        if (randomType == RANDOM_TYPE_ALNUM) {
            str = "3456789987654334567899876543";
        } else if (randomType == RANDOM_TYPE_ALPHA) {
            str = "abcdefghjkmnpqrstuvwxyYXWVUTSRQPNMKJHGFEDCBAyxwvutsrqpnmkjhgfedcbaABCDEFGHJKMNPQRSTUVWXY";
        } else {
            str = "yxwvutsrqpnmkjhgfedcba3456789ABCDEFGHJKMNPQRSTUVWXY99876543ABCDEFGHJKMNPQRSTUVWXYabcdefghjkmnpqrstuvwxy";
        }

        Random rnd = new Random();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < len; i++) {
            int index = rnd.nextInt(str.length());
            sb.append(str.charAt(index));
        }

        return sb.toString();
    }
}

Related

  1. getRandomString(int cantidad, boolean mayusculas, boolean minusculas, boolean numeros, boolean simbolos, boolean repetir)
  2. getRandomString(int count)
  3. getRandomString(int len)
  4. getRandomString(int len)
  5. getRandomString(int len)
  6. getRandomString(int len, boolean ascii_only)
  7. getRandomString(int lenght)
  8. getRandomString(int length)
  9. getRandomString(int length)