可用于生成验证码,随机密码等等.
//随机码生成
//int nRandomCount 长度
//boolean isNumber 是否是数字代码
//By longware
public String getRandomString(int nRandomCount, boolean isNumber) {
char[] a = null;
if (isNumber) {
a = new char[10];
for (int i = 48, j = 0; i <= 57; i++, j++) {
a[j] = (char) i;
}
} else {
// ASCII 48~57,String 0~9;
// ASCII 65~90,String A-Z;
// ASCII 97~122,String a-z;
a = new char[62];
for (int i = 48, j = 0; i <= 122; i++) {
if ((i > 57 && i < 65) || (i > 90 && i < 97)) {
continue;
} else {
a[j] = (char) i;
j++;
}
}
}
String strRand = "";
int LengthOfRandom = a.length;
Random random = new Random();
for (int i = 0; i < nRandomCount; i++) {
int nRand = random.nextInt(LengthOfRandom);
strRand += a[nRand];
}
return strRand;
}