View Javadoc
1   package com.foxinmy.weixin4j.util;
2   
3   import java.util.Random;
4   import java.util.UUID;
5   
6   /**
7    * 随机码工具类
8    * 
9    * @className RandomUtil
10   * @author jinyu(foxinmy@gmail.com)
11   * @date 2014年10月22日
12   * @since JDK 1.6
13   * @see
14   */
15  public class RandomUtil {
16  
17  	private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
18  	private static final String LETTERCHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
19  	private static final String NUMBERCHAR = "0123456789";
20  
21  	/**
22  	 * 返回一个定长的随机字符串(包含数字和大小写字母)
23  	 * 
24  	 * @param length
25  	 *            随机数的长度
26  	 * @return
27  	 */
28  	public static String generateString(int length) {
29  		StringBuilder sb = new StringBuilder(length);
30  		Random random = new Random();
31  		for (int i = 0; i < length; i++) {
32  			sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
33  		}
34  		return sb.toString();
35  	}
36  
37  	/**
38  	 * 返回一个定长的随机纯数字字符串(只包含数字)
39  	 * 
40  	 * @param length
41  	 *            随机数的长度
42  	 * @return
43  	 */
44  	public static String generateStringByNumberChar(int length) {
45  		StringBuilder sb = new StringBuilder(length);
46  		Random random = new Random();
47  		for (int i = 0; i < length; i++) {
48  			sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
49  		}
50  		return sb.toString();
51  	}
52  
53  	/**
54  	 * 返回一个定长的随机纯字母字符串(只包含大小写字母)
55  	 * 
56  	 * @param length
57  	 *            随机数的长度
58  	 * @return
59  	 */
60  	public static String generateStringByLetterCharr(int length) {
61  		StringBuilder sb = new StringBuilder(length);
62  		Random random = new Random();
63  		for (int i = 0; i < length; i++) {
64  			sb.append(LETTERCHAR.charAt(random.nextInt(LETTERCHAR.length())));
65  		}
66  		return sb.toString();
67  	}
68  
69  	/**
70  	 * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
71  	 * 
72  	 * @param length
73  	 *            随机数的长度
74  	 * @return
75  	 */
76  	public static String generateLowerString(int length) {
77  		return generateStringByLetterCharr(length).toLowerCase();
78  	}
79  
80  	/**
81  	 * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
82  	 * 
83  	 * @param length
84  	 *            随机数的长度
85  	 * @return
86  	 */
87  	public static String generateUpperString(int length) {
88  		return generateStringByLetterCharr(length).toUpperCase();
89  	}
90  
91  	/**
92  	 * 随机获取UUID字符串(无中划线)
93  	 * 
94  	 * @return UUID字符串
95  	 */
96  	public static String getUUID() {
97  		String uuid = UUID.randomUUID().toString();
98  		return uuid.substring(0, 8) + uuid.substring(9, 13)
99  				+ uuid.substring(14, 18) + uuid.substring(19, 23)
100 				+ uuid.substring(24);
101 	}
102 
103 	public static void main(String[] args) {
104 		System.out.println(System.nanoTime());
105 		System.out.println(System.currentTimeMillis());
106 	}
107 }