官方文檔: https://www.hutool.cn/docs/#/core/工具類/隨機工具-RandomUtil文章來源:http://www.zghlxwxcb.cn/news/detail-600057.html
1.原生Java代碼實現(xiàn):
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 數(shù)字和26個字母組成
private static final Random RANDOM = new SecureRandom(); // SecureRandom是加密且線程安全的
/**
* 獲取長度為 6 的隨機字母+數(shù)字
* @return 隨機數(shù)字
*/
public static String getRandomNumber() {
char[] nonceChars = new char[16]; //指定長度為6位/自己可以要求設置
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
2.Hutool工具實現(xiàn):
public static void main(String[] args) {
// 小寫字母+數(shù)字,例:d2qdw920d5
String randomString1 = RandomUtil.randomString(10);
// 大寫字母+數(shù)字,例:I6R7Q38JWC
String randomStringUpper = RandomUtil.randomStringUpper(10);
// 只含有abc,例:bcccbcccac
String randomString2 = RandomUtil.randomString("abc", 10);
// 大寫字母+小寫字母+數(shù)字,例:qf0Vr2TK3J
String randomString3 = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 10);
// 數(shù)字,例:8
char randomNumber1 = RandomUtil.randomNumber();
// 小寫字母+大寫字母中,不含有0123456789,例:nmjjyscmvq
String randomStringWithoutStr = RandomUtil.randomStringWithoutStr(10, "0123456789");
// 生成小寫字母+數(shù)字的其中一個字符,例:m
char randomChar1 = RandomUtil.randomChar();
// 生成0123456789中一個字符,例:7
char randomNumber2 = RandomUtil.randomNumber();
// 生成-!?中一個字符,例:?
char randomChar2 = RandomUtil.randomChar("-!?");
}
整理完畢,完結撒花~文章來源地址http://www.zghlxwxcb.cn/news/detail-600057.html
到了這里,關于Hutool 生成隨機數(shù)和隨機字符串的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!