Java如何生成随机的字母数字字符串?

下面的代码片段演示了如何使用 Apache Commons Text 库中的 RandomStringGenerator 类生成随机字符串。要创建生成器的实例,我们可以使用 RandomStringGenerator.Builder ()类 build ()方法。生成器类还可以帮助我们配置生成器的属性。在调用 build ()方法之前,我们可以使用以下方法设置构建器的属性:

  • withinRange() 指定在生成的字符串中允许的最小和最大代码点。

  • filteredBy()将生成的字符串中的字符限制为与至少提供的谓词之一匹配的字符。谓词的一些枚举:CharacterPredicates.DIGITS,CharacterPredicates.LETTERS。

  • selectFrom() 将生成的字符串中的字符限制为在提供的“字符”列表中匹配的字符。

  • usingRandom() 覆盖默认的随机性来源。

在根据定义的属性配置并构建了生成器之后,我们可以使用的generate()方法生成随机字符串RandomStringGenerator。有两种方法可用:

  • generate(int length) 生成一个随机字符串,其中包含指定数量的代码点。

  • generate(int minLengthInclusive, int maxLengthInclusive) 生成一个随机字符串,其中包含最小(包括)和最大(包括)。

这是您的代码段:

package org.nhooo.example.commons.text;

import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;

public class RandomStringDemo {
    public static void main(String[] args) {
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .withinRange('0', 'z')
            .filteredBy(CharacterPredicates.DIGITS, CharacterPredicates.LETTERS)
            .build();

        for (int i = 0; i < 10; i++) {
            System.out.println(generator.generate(10, 20));
        }
    }
}

以下是生成的随机字母数字字符串的示例:

iDp323cGhbnvHBq
fuOHpaM0x8B9eFBR2tr
T8JmM8jeRN
SSP1ZsFsIyP
GPr7rDbwr33zO
s7HkOlcT6gLQoWOfV6
WMgmVfhxp0
OTj9UUBdnT51TgACK
VmRzheeRyVZJKGo7
xzyD31Vk7Fx

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-text/1.7/commons-text-1.7.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.7</version>
</dependency>

Maven中央