apache.commons.text生成随机字符串
本文使用到的第三方jar包为:commons-text-1.8.jar
另外:使用此包还需要引入lang3包(依赖lang3):commons-lang3-3.8.1.jar
下载地址:https://commons.apache.org/proper/commons-text/download_text.cgi
说明书:https://commons.apache.org/proper/commons-text/apidocs/index.html
导包:(只使用到RandomStringGenerator工具类,所以只导下面的的包)
import org.apache.commons.text.RandomStringGenerator;
如果未引入依赖包,则会报下列异常:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/Validate
Apache commons text 是一个专注于处理字符串的算法的库。
org.apache.commons.text包下有一个类:RandomStringGenerator.Builder,该类用于生成RandomStringGenerator实例的生成器。
该类提供了 build(),withinRange(char[]… pairs)等成员方法
build():使用指定的属性构建RandomStringGenerator。
withinRange(char[]… pairs)指定生成的字符串中允许的最小和最大字符的数组。
生成字符串代码如下:
import org.apache.commons.text.RandomStringGenerator;
public class RandomStringTest {
public static void main(String[] args) {
/**
* 随机生成字符串
*/
RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange(new char[]{'\u4e00', '\u9fa5'}).build();
// withinRange() 指定生成的字符串的区间
//.withinRange(new char[]{'a', 'z'}, new char[]{'A', 'Z'}, new char[]{'0', '9'}).build();
// '\u4e00', '\u9fa5':这是指中文区间
//'a', 'z':这是字母区间a-z
// 生成长度为10的随机字符串
System.out.println(generator.generate(10));
}
}
运行结果:(此处是生成随机中文:’\u4e00’, ‘\u9fa5’)
灁挫欷耵螳帰鶽赠麜讦
(ps:一个字都不认识)