commons -lang(2) RandomStringUtils RandomUtils

时间:2023-03-09 15:29:38
commons -lang(2)  RandomStringUtils RandomUtils

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

1.RandomStringUtils

commons -lang(2)  RandomStringUtils RandomUtils

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

     //模拟实现random(5,"helloworld")
public static String getRandomString(int count,String str) {
if(str != null) {
if(!StringUtils.isBlank(str)) {
if(count <= 0) {
return "";
}
char[] charArray = str.toCharArray();
int index;
char[] newArray = new char[count];
for(int i=0;i<count;i++) {
index = RandomUtils.nextInt(0,charArray.length);
newArray[i] = str.charAt(index);
}
return new String(newArray);
}
}
return null;
}

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

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

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

     //指定数字的个数
public static String getRandomAlphanumeric(int count,int numbers) {
if(count <=0 || numbers <=0) {
return "";
}
//纯数字
if(numbers>=count) {
return RandomStringUtils.randomNumeric(numbers);
}
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
String str = RandomStringUtils.random(count-numbers, letters) + RandomStringUtils.randomNumeric(numbers);
//打乱位置
char[] charArray = str.toCharArray();
List<Character> list = new ArrayList<Character>();
for (Character character : charArray) {
list.add(character);
}
Collections.shuffle(list);
for(int i=0;i<list.size();i++) {
charArray[i] = list.get(i);
}
return new String(charArray);
}

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

2.RandomUtils

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

commons -lang(2)  RandomStringUtils RandomUtils

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