Java Random String getString(int length)

Here you can find the source of getString(int length)

Description

get String

License

Apache License

Declaration

public static final String getString(int length) 

Method Source Code


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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

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

    public static final String getString(int length) {
        if (length <= 0) {
            length = 6;//  w w  w  . j  a v  a2 s .c  o  m
        }
        // merge array
        List<String> randomLowerLetterList = Arrays.asList(randomLowerLetter);
        List<String> randomUpperLetterList = Arrays.asList(randomUpperLetter);
        List<String> randomNumberList = Arrays.asList(randomNumber);
        List<String> randomList = new ArrayList<String>();
        randomList.addAll(randomLowerLetterList);
        randomList.addAll(randomUpperLetterList);
        randomList.addAll(randomNumberList);
        // generate random length number
        int listLength = randomList.size();
        List<Integer> indexList = new ArrayList<Integer>();
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < length; i++) {
            int n = random.nextInt(listLength - 1);
            indexList.add(n);
        }
        String randomPassword = "";
        for (Integer indexNumber : indexList) {
            randomPassword = randomPassword + randomList.get(indexNumber);
        }
        return randomPassword;
    }
}

Related

  1. getRandomStringByLength(int length)
  2. getRandomStringForDate()
  3. getRandomStringOfLetters(int length)
  4. getString(int length)
  5. getString(int length)
  6. getString(int n, int arg[])
  7. randomCharacter(String availableValues)
  8. randomFileString()
  9. randomFixedByteLengthUnicodeString(Random r, int length)