欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java随机字符串生成示例

程序员文章站 2024-02-24 10:11:40
复制代码 代码如下:package com.phyl.password; import java.util.arraylist;import java.util.arra...

复制代码 代码如下:

package com.phyl.password;

import java.util.arraylist;
import java.util.arrays;
import java.util.random;
/**
 * 字符随机生成类
 * @author asus
 *
 */
public class password {

 /**
  * 密码类型枚举
  * @author asus
  */
 public static enum type {
  /**
   * 字符型
   */
  letter,
  /**
   * 大写字符型
   */
  capital,
  /**
   * 数字型
   */
  number,
  /**
   * 符号型
   */
  sign,
  /**
   * 大+小字符 型
   */
  letter_capital,
  /**
   * 小字符+数字 型
   */
  letter_number,
  /**
   * 大+小字符+数字 型
   */
  letter_capital_number,
  /**
   * 大+小字符+数字+符号 型
   */
  letter_capital_number_sign
 }

 private static string[] lowercase = {
   "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"};

 private static string[] capital = {
   "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"}; 

 private static string[] number = {
   "1","2","3","4","5","6","7","8","9","0"};

 private static string[] sign = {
   "~","!","@","#","$","%","^","&","*","(",")","_","+","`","-","=",
   "{","}","|",":","\"","<",">","?",
   "[","]","\\",";","'",",",".","/"};

 /**
  * 静态随机数
  */
 private static random random = new random();

 public static void main(string[] args) {
  system.out.println(password.getrandom(24, password.type.capital));
 }

 /**
  * 获取随机组合码
  * @param num 位数
  * @param type 类型
  * @type
  * <br>字符型 letter,
  * <br>大写字符型 capital,
  * <br>数字型 number,
  * <br>符号型 sign,
  * <br>大+小字符 型 letter_capital,
  * <br>小字符+数字 型 letter_number,
  * <br>大+小字符+数字 型 letter_capital_number,
  * <br>大+小字符+数字+符号 型 letter_capital_number_sign
  */
 public static string getrandom(int num,type type){
  arraylist<string> temp = new arraylist<string>();
  stringbuffer code = new stringbuffer();
  if(type == type.letter){
   temp.addall(arrays.aslist(lowercase));
  }else if(type == type.capital){
   temp.addall(arrays.aslist(capital));
  }else if(type == type.number){
   temp.addall(arrays.aslist(number));
  }else if(type == type.sign){
   temp.addall(arrays.aslist(sign));
  }else if(type == type.letter_capital){
   temp.addall(arrays.aslist(lowercase));
   temp.addall(arrays.aslist(capital));
  }else if(type == type.letter_number){
   temp.addall(arrays.aslist(lowercase));
   temp.addall(arrays.aslist(number));
  }else if(type == type.letter_capital_number){
   temp.addall(arrays.aslist(lowercase));
   temp.addall(arrays.aslist(capital));
   temp.addall(arrays.aslist(number));
  }else if(type == type.letter_capital_number_sign){
   temp.addall(arrays.aslist(lowercase));
   temp.addall(arrays.aslist(capital));
   temp.addall(arrays.aslist(number));
   temp.addall(arrays.aslist(sign));
  }
  for (int i = 0; i < num; i++) {
   code.append(temp.get(random.nextint(temp.size())));
  }
  return code.tostring();
 }

}