自己实现随机字符串的生成。
parent
956da350ed
commit
55395ed327
|
@ -0,0 +1,18 @@
|
|||
package xyz.zhouxy.plusone.util;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public final class RandomUtil {
|
||||
private RandomUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static String randomStr(char[] sourceCharacters, int length) {
|
||||
ThreadLocalRandom random = ThreadLocalRandom.current();
|
||||
char[] result = new char[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
result[i] = sourceCharacters[random.nextInt(sourceCharacters.length)];
|
||||
}
|
||||
return String.valueOf(result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package xyz.zhouxy.plusone.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Slf4j
|
||||
class RandomUtilTests {
|
||||
|
||||
@Test
|
||||
void testRandom() {
|
||||
String[] s = new String[20];
|
||||
for (int i = 0; i < 20; i++) {
|
||||
s[i] = RandomUtil.randomStr(
|
||||
"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM~`!@#$%^&*()_-+={[\\|/:;\"',.<>?]}"
|
||||
.toCharArray(),
|
||||
28);
|
||||
}
|
||||
log.info("{}", Arrays.toString(s));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue