java实现随机生成验证码
import java.util.concurrent.ThreadLocalRandom;/*
生成验证码的工具
可动态配置验证码长度*/
public class CodeUtils {public static void main(String[] args) {//随机生成5个长度为4的验证码for (int i = 0; i < 5; i++) {System.out.println(CodeUtils.getCode(4));}for (int i = 0; i < 5; i++) {System.out.println(CodeUtils.getCode(6));}}public static String getCode(int len){//验证码生成范围String s = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";char[] c = s.toCharArray();StringBuffer str = new StringBuffer("");ThreadLocalRandom current = ThreadLocalRandom.current();for (int i = 0; i < len; i++) {char code = c[current.nextInt(0,s.length())];str.append(code);}return str.toString();}
}
运行结果: