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用處更多一點

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM