java随机产生字符串
2009-05-04 18:21
344 查看
今天在做一个注册模块,要求用到验证码。自己就试着写了一个。
/**
* 产生随机字符串
* */
private static Random randGen = null;
private static char[] numbersAndLetters = null;
private static Object initLock = new Object();
public static final String randomString(int length) {
if (length < 1) {
return null;
}
if (randGen == null) {
synchronized (initLock) {
if (randGen == null) {
randGen = new Random();
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
}
}
}
char [] randBuffer = new char[length];
for (int i=0; i<randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}
调用此方法randomString(int),int是字符串的长度,即可产生指定长度的随机字符串。
/**
* 产生随机字符串
* */
private static Random randGen = null;
private static char[] numbersAndLetters = null;
private static Object initLock = new Object();
public static final String randomString(int length) {
if (length < 1) {
return null;
}
if (randGen == null) {
synchronized (initLock) {
if (randGen == null) {
randGen = new Random();
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
}
}
}
char [] randBuffer = new char[length];
for (int i=0; i<randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}
调用此方法randomString(int),int是字符串的长度,即可产生指定长度的随机字符串。
相关文章推荐
- 用java中的Math.random()函数产生一个简单的随机字符串
- java产生随机字符串的各种方法------工具类(包含过滤表情方法)
- java 随机产生字符串
- java 产生随机字符串
- JAVA工具类(14)----UUID工具类,产生随机字符串主键
- Java实现产生随机字符串主键的UUID工具类
- java产生随机字符串
- java 随机产生字符串
- HeadFirstJava学习心得——随机字符串的产生
- 产生长度为10以内整数的随机字符串(java)
- Java随机产生数字字母字符串
- 产生随机字符串
- 随机数字 浮点数 字符串产生
- 高并发下产生大量,随机,唯一的字符串,并输出到文件中
- java:产生随机10个1000以内随机整数(从大到小)
- 【Java】获取随机字符串的两种方法
- Java生成随机字符串
- 【代码笔记】iOS-产生随机字符串
- 随机产生一个字符串
- java随机产生验证码最简单方式