/** * 獲取隨機字符串,由數字、大小寫字母組成 * @param bytes:生成的字符串的位數 * @return * @author */ public static String getRandomStr(int bytes){ StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < bytes; i++) { //隨機判斷判斷該字符是數字還是字母 String choice = random.nextInt(2) % 2 == 0 ? "char" : "num"; if ("char".equalsIgnoreCase(choice)) { //隨機判斷是大寫字母還是小寫字母 int start = random.nextInt(2) % 2 == 0 ? 65 : 97; sb.append((char) (start + random.nextInt(26))); } else if ("num".equalsIgnoreCase(choice)) { sb.append(random.nextInt(10)); } } return sb.toString(); }