import java.security.SecureRandom
// 定义生成随机字符串的函数
static def randomString(int length) {
// 首先定义一个随机数生成器
SecureRandom secureRandom = new SecureRandom()
// 使用可打印的 ASCII 字符作为生成字符串的字符集合
String characters = ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
// 用 StringBuilder 保存生成的字符串
StringBuilder sb = new StringBuilder()
// 循环生成指定长度的随机字符串
for (int i = 0; i < length; i++) {
// 从字符集合中随机选择一个字符
int randomIndex = secureRandom.nextInt(characters.length())
char randomChar = characters.charAt(randomIndex)
// 将选择的字符添加到字符串中
sb.append(randomChar)
}
// 返回生成的随机字符串
return sb.toString()
}
// 使用示例:生成长度为 10 的随机字符串
def randomStr = randomString(10)
01-23
07-26
134
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-21