一个生成java随机数字,数字字符串的方法
By:Roy.LiuLast updated:2015-02-05
在写程序中,经常会用到随机数,或者随机字符串,这里收藏一个公共的方法,以后也不用另外写了,一个参表示生成的长度,另外一个表示类型.
调用起来很简单的。
public static String getCode(int passLength, int type) { StringBuffer buffer = null; StringBuffer sb = new StringBuffer(); Random r = new Random(); r.setSeed(new Date().getTime()); switch (type) { case 0: buffer = new StringBuffer("0123456789"); break; case 1: buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz"); break; case 2: buffer = new StringBuffer("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); break; case 3: buffer = new StringBuffer( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); break; case 4: buffer = new StringBuffer( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); sb.append(buffer.charAt(r.nextInt(buffer.length() - 10))); passLength -= 1; break; case 5: String s = UUID.randomUUID().toString(); sb.append(s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24)); } if (type != 5) { int range = buffer.length(); for (int i = 0; i < passLength; ++i) { sb.append(buffer.charAt(r.nextInt(range))); } } return sb.toString(); }
调用起来很简单的。
From:一号门
Previous:改变Eclipse 的主题, 使眼镜很舒服
COMMENTS