java随机生成字符串必须是大写字母+小写字母+数字

mac2025-08-22  3

package cn.cm.util; /** * * @author zhangshengjun * 时间: 2018年10月9日 * 内容:随机生成字符串必须是大写字母+小写字母+数字长度不能少于8 */ public class RandomUtils { /** * 单元测试 * 运行: java RandomStr 16 (生成长度为16的字符串) */ public static void main(String[] args){ // System.out.println(randomStr(8)); System.out.println(randomPublicKey16()); } /** * 返回随机字公钥字符串,同时包含数字、大小写字母、+、=、\ * @return String 随机字符串 16位 */ public static String randomPublicKey16(){ //数组,用于存放随机字符 char[] chArr = new char[16]; //为了保证必须包含数字、大小写字母 chArr[0] = (char)('0' + StandardRandom.uniform(0,10)); chArr[1] = (char)('A' + StandardRandom.uniform(0,26)); chArr[2] = (char)('a' + StandardRandom.uniform(0,26)); chArr[3] = (char)('+' + StandardRandom.uniform(0,1)); chArr[4] = (char)('=' + StandardRandom.uniform(0,1)); chArr[5] = (char)('/' + StandardRandom.uniform(0,1)); char[] codes = { '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J', 'K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z','a','b','c','d', 'e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x', 'y','z','+','=','/'}; //charArr[6..len-1]随机生成codes中的字符 for(int i = 6; i < 16; i++){ chArr[i] = codes[StandardRandom.uniform(0,codes.length)]; } //将数组chArr随机排序 for(int i = 0; i < 16; i++){ int r = i + StandardRandom.uniform(16 - i); char temp = chArr[i]; chArr[i] = chArr[r]; chArr[r] = temp; } return new String(chArr); } } package cn.cm.util; import java.util.Random; /** * * @author zhangshengjun * 时间: 2018年10月9日 * 内容:辅助随机生成字符串类 */ public final class StandardRandom { //随机数生成器 private static Random random; //种子值 private static long seed; //静态代码块,初始化种子值及随机数生成器 static { seed = System.currentTimeMillis(); random = new Random(seed); } //私有构造函数,禁止实例化 private StandardRandom() {} /** * 设置种子值 * @param s 随机数生成器的种子值 */ public static void setSeed(long s){ seed = s; random = new Random(seed); } /** * 获取种子值 * @return long 随机数生成器的种子值 */ public static long getSeed(){ return seed; } /** * 随机返回0到1之间的实数 [0,1) * @return double 随机数 */ public static double uniform(){ return random.nextDouble(); } /** * 随机返回0到N-1之间的整数 [0,N) * @param N 上限 * @return int 随机数 */ public static int uniform(int N){ return random.nextInt(N); } /** * 随机返回0到1之间的实数 [0,1) * @return double 随机数 */ public static double random(){ return uniform(); } /** * 随机返回a到b-1之间的整数 [a,b) * @param a 下限 * @param b 上限 * @return int 随机数 */ public static int uniform(int a,int b){ return a + uniform(b - a); } /** * 随机返回a到b之间的实数 * @param a 下限 * @param b 上限 * @return double 随机数 */ public static double uniform(double a,double b){ return a + uniform() * (b - a); } }
最新回复(0)