package com.demo.lib.common.util.common; import java.util.Random; /** * Random Utils * * @author Trinea 2012-5-12 */ public class RandomUtils { public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String NUMBERS = "0123456789"; public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; /** * get a fixed-length random string, its a mixture of uppercase, lowercase letters and numbers * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomNumbersAndLetters(int length) { return getRandom(NUMBERS_AND_LETTERS, length); } /** * get a fixed-length random string, its a mixture of numbers * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomNumbers(int length) { return getRandom(NUMBERS, length); } /** * get a fixed-length random string, its a mixture of uppercase and lowercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomLetters(int length) { return getRandom(LETTERS, length); } /** * get a fixed-length random string, its a mixture of uppercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomCapitalLetters(int length) { return getRandom(CAPITAL_LETTERS, length); } /** * get a fixed-length random string, its a mixture of lowercase letters * * @param length * @return * @see RandomUtils#getRandom(String source, int length) */ public static String getRandomLowerCaseLetters(int length) { return getRandom(LOWER_CASE_LETTERS, length); } /** * get a fixed-length random string, its a mixture of chars in source * * @param source * @param length * @return */ public static String getRandom(String source, int length) { return StringUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length); } /** * get a fixed-length random string, its a mixture of chars in sourceChar * * @param sourceChar * @param length * @return */ public static String getRandom(char[] sourceChar, int length) { if (sourceChar == null || sourceChar.length == 0 || length < 0) { return null; } StringBuilder str = new StringBuilder(length); Random random = new Random(); for (int i = 0; i < length; i++) { str.append(sourceChar[random.nextInt(sourceChar.length)]); } return str.toString(); } }