生成随机8位或小于等于18位数字,生成随机任意位数的字符串
话不多说,直接上代码
- 1、使用java的util包下的Random类,获取8位随机数字:
//实例化随机数对象
Random random = new Random();
//获取19位的数字
long nextLong = random.nextLong();
//将19位long类型的数字转化为字符串
String value = String.valueOf(nextLong);
//截取8位,索引从0开始, 因为可能位负数 负数前面会带有-号, 所以从1索引开始截取
String substring = value.substring(1, 9);
System.out.println(substring);
- 2、使用java的util包下的Random类,生成<=18位随机数字:
//生成<=18位的随机数字
public String generateRandom(int number) {
//实例化随机数对象
Random random = new Random();
//获取19位的数字
long nextLong = random.nextLong();
//将19位long类型的数字转化为字符串
String value = String.valueOf(nextLong);
//截取number位
String substring = value.substring(1, number);
return substring;
}
- 3、使用org.apache.commons.lang3.RandomUtils类,生成随机数字:
long num = RandomUtils.nextLong();
System.out.println(num);
<!-- 依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
- 4、使用org.apache.commons.lang3.RandomStringUtils类,生成任意数量的随机字符:
//生成20个随机字符
String str = RandomStringUtils.randomAlphanumeric(20);
System.out.println(str);