cy
2022-06-21 129904537f66509f97b285e7eb4f42b3dc349dd0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package cn.ksource.core.test;
 
import java.io.File;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
 
import cn.ksource.core.util.ConvertUtil;
 
public class TestUtil {
 
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(getRandomEnglishCharacters(6, 26));
        }
    }
    
    /**
     * 获取英文随机数
     * @param minLength
     * @param maxLength
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Jun 8, 2014 5:24:44 PM
     */
    public static String getRandomEnglishCharacters(int minLength, int maxLength){
        String content = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String result = "";
        int length = getRandom(minLength, maxLength);
        int contentLength = content.length();
        int start = getRandom(0, contentLength-length);
        result = content.substring(start, start+length);
        return result;
    }
    
    
    /**
     * 获得指定长度的随机汉字
     * @param minLength
     * @param maxLength
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Jun 8, 2014 5:17:02 PM
     */
    public static String getRandomChineseCharacters(int minLength,int maxLength){
        String filePath = TestUtil.class.getResource("/cn/ksource/core/test/")+"test_text.txt";
        String content = "";
        String truePath = StringUtils.removeStart(filePath, "file:/");
        String result = "";
        try {
            content = FileUtils.readFileToString(new File(truePath), "utf-8");
            int length = getRandom(minLength, maxLength);
            int contentLength = content.length();
            int start = getRandom(0, contentLength-length);
            result = content.substring(start, start+length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 获取随机数
     * @param max
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Jun 8, 2014 4:45:47 PM
     */
    public static int getRandom(int min,int max){
        for (int i = 0; i < 100000; i++) {
            double random = Math.random();
            int num = ConvertUtil.obj2Int(String.valueOf(random * max));
            if (num < max && num > min) {
                return num;
            }
        }
        return 0;
    }
    
}