java 生成随机字符串

1.生成之指定位数的随机字符串

 1     /**
 2      * 随机基数
 3      */
 4     private static char[] charset = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', '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', 'G', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
 5  
 6   /**
 7      * 获取指定位数的随机字符串
 8      *
 9      * @param len 指定位数
10      * @return
11      */
12     private static String getRandomStr(int len) {
13         StringBuffer sb = new StringBuffer(len);
14         for (int i = 0; i < 3; i++) {
15             char c = charset[new Random().nextInt(charset.length)];
16             sb.append(c);
17         }
18         return sb.toString();
19     }

2、指定位数补零

 1  /**
 2      * 不足指定位数前补0 
 3      *
 4      * @param length 长度
 5      * @param source 需要补位的数字
 6      * @return
 7      */
 8     private static String beforeZeroFill(int length, int source) {
 9         return String.format("%0" + length + "d", source);
10     }

 

posted @ 2018-07-27 17:03  爱,诗意永存  阅读(304)  评论(0编辑  收藏  举报