http://hi.baidu.com/yinfuqing666/blog/item/b9c3a0d21917e00e3af3cf28.html
http://hi.baidu.com/samuel_vong/blog/item/95471f7e2cdab33d0cd7dad1.html
使用 RandomStringUtils 类来生成随机码/随机数 http://www.oschina.net/code/snippet_12_576
实现方法一:
引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class RandomFileName { /** * 产生一个随机的字符串 * * @param 字符串长度 * @return */ public static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } public static void main(String[] args) { System.out.println(RandomFileName.getRandomString(5)); } } |
实现方法二:
引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class RandomFileName2 { /** * 产生一个随机的字符串 * * @param 字符串长度 * @return */ public static String getRandomString(int length) { Random random=new Random(); StringBuffer sb=new StringBuffer(); for(int i=0;i<length;i++){ int number=random.nextInt(3); long result=0; switch(number){ case 0: result = Math.round(Math.random()*25+65); sb.append(String.valueOf((char)result)); break; case 1: result = Math.round(Math.random()*25+97); sb.append(String.valueOf((char)result)); break; case 2: sb.append(String.valueOf(new Random().nextInt(10))); break; } } return sb.toString(); } public static void main(String[] args) { System.out.println(RandomFileName2.getRandomString(10)); } } |