Java生成指定长度的随机字符串的三种方法

1 自定义随机字符串方法一(A-Z,a-z,0-9)

//生成指定length的随机字符串(A-Z,a-z,0-9)
public static String getRandomString(int length) {
    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
        int number = random.nextInt(str.length());
        sb.append(str.charAt(number));
    }
    return sb.toString();
}

 

2 自定义随机字符串方法二(A-Z,a-z,0-9)

//生成指定length的随机字符串(A-Z,a-z,0-9)
public static String getRandomString2(int length) {
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
        int number = random.nextInt(3);
        long result = 0;
        switch (number) {
            case 0:
                result = Math.round(Math.random() * 25 + 65);
                sb.append(String.valueOf((char) result));
                break;
            case 1:
                result = Math.round(Math.random() * 25 + 97);
                sb.append(String.valueOf((char) result));
                break;
            case 2:
                sb.append(String.valueOf(new Random().nextInt(10)));
                break;
        }
    }
    return sb.toString();
}

 

3 org.apache.commons.lang包下的RandomStringUtils类

//生成指定length的随机字符串(A-Z,a-z,0-9)
String str = RandomStringUtils.randomAlphanumeric(32);

 

  运行结果

Java生成指定长度的随机字符串的三种方法_第1张图片

你可能感兴趣的:(Java生成指定长度的随机字符串的三种方法)