方法一:
方法二:
/**
* 获取16位以内的随机数字符串
* @return
*/
public static String getNonceStr(int num){
// Math.random()的结果是个double类型的值,区间为[0.0,1.0)
if(num>0&&num<=16){
String str=String.valueOf(Math.random()).substring(2);//16位随机数
return str.substring(0,num);
}
return "";
}
方法二:
import java.util.Random;
public class StringDemo {
public static void main(String[] args) {
String temp=generateRandomString();
System.out.println("长度8位的随机字符串="+temp);
}
/**
* 随机生成字符串
*
* @return
*/
private static String generateRandomString() {
final int FIXED=8;//生成的随机字符串长度
final String originStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
final Random random = new Random();
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < FIXED; i++) {
final Character ch = originStr.charAt(random.nextInt(originStr.length()));
buffer.append(ch);
}
return buffer.toString();
}
}