RandomUtils.java
3.35 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.diligrp.assistant.shared.util;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
/**
* 随机数工具类
*/
public final class RandomUtils {
/**
* 生成随机字符串, a-z A-Z 0-9
*/
public static String randomString(int length){
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++){
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
/**
* 生成固定长度的随机数字字符串
*/
public static String randomNumber(int length) {
AssertUtils.isTrue(length > 0, "invalid length");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i ++) {
int next = ThreadLocalRandom.current().nextInt(10);
builder.append((char) (48 + next));
}
return builder.toString();
}
/**
* 生成8位随机码(数字0~9+大写字母A~Z)
*/
public static String randomCode() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; i++) {
int a = Math.abs((new Random()).nextInt(32));
if (a <= 9) {
sb.append((char) (a + 48));
} else if (a < 33) {
if ((a + 55) == 79 || (a + 55) == 73) {
sb.append((char) (a + 63));
} else {
sb.append((char) (a + 55));
}
}
}
return sb.toString();
}
/**
* 功能描述:获取随机字符串
*/
public static String randomString(int length, String original) {
if (length <= 0 || ObjectUtils.isEmpty(original)) {
return null;
}
StringBuilder sb = new StringBuilder();
int len = original.length();
for (int i = 0; i < length; i++) {
int round = (int) Math.round(Math.random() * (len - 1));
sb.append(original.charAt(round));
}
return sb.toString();
}
/**
* UUID随机数,移除 "-"
*/
public static String randomUUID() {
return randomUUID(true);
}
public static String randomUUID(boolean upperCase) {
UUID uuid = UUID.randomUUID();
long mostSigBits = uuid.getMostSignificantBits();
long leastSigBits = uuid.getLeastSignificantBits();
return (digits(mostSigBits >> 32, 8, upperCase) +
digits(mostSigBits >> 16, 4, upperCase) +
digits(mostSigBits, 4, upperCase) +
digits(leastSigBits >> 48, 4, upperCase) +
digits(leastSigBits, 12, upperCase));
}
public static String randomCaptcha() {
return String.valueOf((int) ((Math.random() * ((1 << 3) + 1) + 1) * 1000));
}
/**
* 生成随机区间数字
*/
public static int randomInt(int min, int max) {
return min + (int)(Math.random() * (max + 1 - min));
}
private static String digits(long val, int digits, boolean upperCase) {
long hi = 1L << (digits * 4);
String hexDigits = Long.toHexString(hi | (val & (hi - 1))).substring(1);
return upperCase ? hexDigits.toUpperCase() : hexDigits;
}
}