随机数工具类
1 /** 2 * <html> 3 * <body> 4 * <P> Copyright 1994 JsonInternational</p> 5 * <p> All rights reserved.</p> 6 * <p> Created on 19941115</p> 7 * <p> Created by Jason</p> 8 * </body> 9 * </html> 10 */ 11 package cn.ucaner.alpaca.framework.utils.math; 12 13 import java.util.Random; 14 15 /** 16 * @Package:cn.ucaner.common.utils.math 17 * @ClassName:RandomUtils 18 * @Description: <p> 随机数工具类</p> 19 * @Author: - Jason 20 * @CreatTime:2017年10月26日 上午10:50:29 21 * @Modify By: 22 * @ModifyTime: 23 * @Modify marker: 24 * @version V1.0 25 */ 26 public class RandomUtils { 27 28 private static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 29 private static final String LETTER_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 30 private static final String NUMBER_CHAR = "0123456789"; 31 32 /** 33 * 获取定长的随机数,包含大小写、数字 34 * @param length 随机数长度 35 * @return 36 */ 37 public static String generateString(int length) { 38 StringBuffer sb = new StringBuffer(); 39 Random random = new Random(); 40 for (int i = 0; i < length; i++) { 41 sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length()))); 42 } 43 return sb.toString(); 44 } 45 46 /** 47 * 获取定长的随机数,包含大小写字母 48 * @param length 随机数长度 49 * @return 50 */ 51 public static String generateMixString(int length) { 52 StringBuffer sb = new StringBuffer(); 53 Random random = new Random(); 54 for (int i = 0; i < length; i++) { 55 sb.append(LETTER_CHAR.charAt(random.nextInt(LETTER_CHAR.length()))); 56 } 57 return sb.toString(); 58 } 59 60 /** 61 * 获取定长的随机数,只包含小写字母 62 * @param length 随机数长度 63 * @return 64 */ 65 public static String generateLowerString(int length) { 66 return generateMixString(length).toLowerCase(); 67 } 68 69 /** 70 * 获取定长的随机数,只包含大写字母 71 * @param length 随机数长度 72 * @return 73 */ 74 public static String generateUpperString(int length) { 75 return generateMixString(length).toUpperCase(); 76 } 77 78 /** 79 * 获取定长的随机数,只包含数字 80 * @param length 随机数长度 81 * @return 82 */ 83 public static String generateNumberString(int length){ 84 StringBuffer sb = new StringBuffer(); 85 Random random = new Random(); 86 for (int i = 0; i < length; i++) { 87 sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length()))); 88 } 89 return sb.toString(); 90 } 91 92 /** 93 * For Test by Jason 94 */ 95 public static void main(String[] args) { 96 System.out.println("***********Test******************"); 97 System.out.println("大小写数字:"+generateString(10)); 98 System.out.println("大小写字母:"+generateMixString(10)); 99 System.out.println("小写字母:"+generateLowerString(10)); 100 System.out.println("大写字母:"+generateUpperString(10)); 101 System.out.println("纯数字:"+generateNumberString(10)); 102 System.out.println("***********Test******************"); 103 } 104 105 } 106 //Outputs 107 //***********Test****************** 108 //大小写数字:SsvQTjEbMW 109 //大小写字母:nJaVyqdmAP 110 //小写字母:ppljietimr 111 //大写字母:YDAGERAFCR 112 //纯数字:8986305301 113 //***********Test******************