How to generate a random alpha-numeric string

前端 未结 30 2571
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

30条回答
  •  忘掉有多难
    2020-11-21 06:06

    Here it is in Java:

    import static java.lang.Math.round;
    import static java.lang.Math.random;
    import static java.lang.Math.pow;
    import static java.lang.Math.abs;
    import static java.lang.Math.min;
    import static org.apache.commons.lang.StringUtils.leftPad
    
    public class RandomAlphaNum {
      public static String gen(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = length; i > 0; i -= 12) {
          int n = min(12, abs(i));
          sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
        }
        return sb.toString();
      }
    }
    

    Here's a sample run:

    scala> RandomAlphaNum.gen(42)
    res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
    

提交回复
热议问题