Java examples for java.util:Random String
Creates random string of characters.
import java.util.Random; public class Main{ protected static final Random rnd = new Random(); protected static final char[] ALPHA_RANGE = new char[] { 'A', 'Z', 'a', 'z' }; /**/*from www .j av a2 s . c om*/ * Creates random string of characters. */ public static String randomAlpha(int count) { return randomRanges(count, ALPHA_RANGE); } /** * Creates random string whose length is the number of characters specified. * Characters are chosen from the multiple sets defined by range pairs. All * ranges must be in acceding order. */ public static String randomRanges(int count, char... ranges) { if (count == 0 || ranges == null) { return StringUtil.EMPTY_STRING; } int i = 0; int len = 0; int lens[] = new int[ranges.length]; while (i < ranges.length) { int gap = ranges[i + 1] - ranges[i] + 1; len += gap; lens[i] = len; i += 2; } char[] result = new char[count]; while (count-- > 0) { char c = 0; int r = rnd.nextInt(len); for (i = 0; i < ranges.length; i += 2) { if (r < lens[i]) { r += ranges[i]; if (i != 0) { r -= lens[i - 2]; } c = (char) r; break; } } result[count] = c; } return new String(result); } }