Java如何生成随机字符串?

Posted 邱海传

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何生成随机字符串?相关的知识,希望对你有一定的参考价值。

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {
    public static final String SOURCES =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

    public static void main(String[] args) {
        RandomString rs = new RandomString();
        System.out.println(rs.generateString(new Random() SOURCES 10));
        System.out.println(rs.generateString(new Random() SOURCES 10));
        System.out.println(rs.generateString(new SecureRandom() SOURCES 15));
        System.out.println(rs.generateString(new SecureRandom() SOURCES 15));
    }

    /**
     * Generate a random string.
     *
     * @param random the random number generator.
     * @param characters the characters for generating string.
     * @param length the length of the generated string.
     * @return
     */
    public String generateString(Random random String characters int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        }
        return new String(text);
    }
}

以上是关于Java如何生成随机字符串?的主要内容,如果未能解决你的问题,请参考以下文章

java如何实现这样的随机数字呢?

java如何随机生成定长的字符串

如何用java随机生成一个字母

Java如何生成随机字符串?

java如何生成随机数?

C语言 如何随机生成字符串