1.生成随机数
import java.security.SecureRandom; public class RandomNumberUtil { private static char[] chars = {‘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‘,‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘}; private static int charLength = chars.length; private static RandomNumberUtil instance = new RandomNumberUtil(); public static RandomNumberUtil getInstance() { return instance; } public static String generateLetterCode(int length) { StringBuilder sb = new StringBuilder(); SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); int index = 0; for (int i = 0;i < length;i++) { index = Math.abs(random.nextInt()) % charLength; char c = chars[index]; sb.append(c); } } catch (Exception e) { } return sb.toString(); } /** * * get random * * @return */ private String generateCheckCode(int randomBit) { // difine chars table of validate code // String chars = "0123456789"; StringBuilder sb = new StringBuilder(); char[] rands = new char[randomBit]; for (int i = 0; i < randomBit; i++) { SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); // int rand = (int) (Math.abs(random.nextInt()) * 10); // rands[i] = chars.charAt(rand); sb.append(Math.abs(random.nextInt()) % 10); } catch (Exception e) { } } return sb.toString(); } /** * get default random * * date(yyyyMMddHHmmss) and random(4) * * @return */ public String getRandom() { return DateUtil.getInstance().getCurrentTime("yyyyMMddHHmmss") + generateCheckCode(4); } /** * * @param randomBit * @return */ public String getDateRandoms(int randomBit) { return DateUtil.getInstance().getCurrentTime("yyyyMMddHHmmss") + generateCheckCode(randomBit); } /** * get random by randomBit * * @param randomBit * @return */ public String getRandom(int randomBit) { return generateCheckCode(randomBit); } /** * * get random by date * * @param formatStr * @return */ public String getRandom(String formatStr) { return DateUtil.getInstance().getCurrentTime(formatStr); } /** * * get random by date and randomBit * * @param formatStr * @param randomBit * @return */ public String getRandom(String formatStr, int randomBit) { return DateUtil.getInstance().getCurrentTime(formatStr) + generateCheckCode(randomBit); } public static void main(String[] args) { // String randomLetters = RandomNumberUtil.generateLetterCode(32); // System.out.println(randomLetters); // System.out.println(randomLetters + " " + randomLetters.length()); System.out.println(RandomNumberUtil.generateLetterCode(50)); System.out.println(RandomNumberUtil.getInstance().getDateRandoms(8)); } }
使用,例:
String id = RandomNumberUtil.getInstance().getDateRandoms(8);//生成流水号