commons -lang(2) RandomStringUtils RandomUtils

上一篇是StringUtils 链接http://www.cnblogs.com/tele-share/p/8060129.html

1.RandomStringUtils

1.1模拟实现random(count,str);

 1     //模拟实现random(5,"helloworld")
 2     public static String getRandomString(int count,String str) {
 3         if(str != null) {
 4             if(!StringUtils.isBlank(str)) {
 5                 if(count <= 0) {
 6                     return "";
 7                 }
 8                 char[] charArray = str.toCharArray();
 9                     int index;
10                     char[] newArray = new char[count];
11                     for(int i=0;i<count;i++) {
12                          index = RandomUtils.nextInt(0,charArray.length);
13                          newArray[i] = str.charAt(index);
14                     }
15                     return new String(newArray);
16             }
17         }
18         return null;
19     }

1.2模拟实现randomAlphanumeric(字母与数字混合,可能没有数字)

 1 //模拟实现randomAlphanumeric(字母与数字混合)
 2     public static String getRandomAlphanumeric(int count) {
 3         if(count <=0) {
 4             return "";
 5         }
 6         String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 7         int number = RandomUtils.nextInt(0,100000);
 8         String str = letters + number;
 9         return getRandomString(count, str);
10     }

1.3模拟实现可以指定数字个数的randomAlphanumeric

 1     //指定数字的个数
 2     public static String getRandomAlphanumeric(int count,int numbers) {
 3         if(count <=0 || numbers <=0) {
 4             return "";
 5         }
 6         //纯数字
 7         if(numbers>=count) {
 8             return RandomStringUtils.randomNumeric(numbers);
 9         }
10         String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
11         String str = RandomStringUtils.random(count-numbers, letters) + RandomStringUtils.randomNumeric(numbers);
12         //打乱位置
13         char[] charArray = str.toCharArray();
14         List<Character> list = new ArrayList<Character>();
15         for (Character character : charArray) {
16             list.add(character);
17         }
18         Collections.shuffle(list);
19         for(int i=0;i<list.size();i++) {
20             charArray[i] = list.get(i);
21         }
22         return new String(charArray);
23     }
24     

总结:RandomStringUtils中的方法可以用于生成随机的验证字符串

2.RandomUtils

这个类感觉与java.util包下的Random类差别不大,还是那几个类似的方法(注意左闭右开)

相比较来说还是RandomStringUtils用处更多一点

原文地址:https://www.cnblogs.com/tele-share/p/8168880.html