生成不定长度的随机字符串:
public class RandomUtils { public static final String allChar="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String generateString(){ StringBuffer sb = new StringBuffer(); Random random = new Random(); int x = random.nextInt(47); for (int i = 0; i < x; i++) { sb.append(allChar.charAt(random.nextInt(allChar.length()))); } return sb.toString(); } //test code public static void main(String[] args) { for (int i = 0; i < 20; i++) { System.out.println(generateString()); } } }
生成指定长度的字符串:
public static final String randomString(int length) { Random randGen = null; char[] numbersAndLetters = null; if (length < 1) { return null; } if (randGen == null) { randGen = new Random(); numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); } char [] randBuffer = new char[length]; for (int i=0; i<randBuffer.length; i++) { randBuffer[i] = numbersAndLetters[randGen.nextInt(71)]; } return new String(randBuffer); }