1 /**
2 * 获取指定长度的随机字符串
3 * @param pwd_len 指定长度
4 * @return
5 */
6 public static String genRandomNum(int pwd_len) {
7 // 35是因为数组是从0开始的,26个字母+10个数字
8 final int maxNum = 36;
9 int i; // 生成的随机数
10 int count = 0; // 生成的密码的长度
11
12 char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
13 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
14 StringBuffer pwd = new StringBuffer("");
15 Random r = new Random();
16 while (count < pwd_len) {
17 // 生成随机数,取绝对值,防止生成负数,
18 i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
19 if (i >= 0 && i < str.length) {
20 pwd.append(str[i]);
21 count++;
22 }
23 }
24
25 return pwd.toString();
26 }