How to generate a random alpha-numeric string

前端 未结 30 2449
忘掉有多难
忘掉有多难 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:04

    An alternative in Java 8 is:

    static final Random random = new Random(); // Or SecureRandom
    static final int startChar = (int) '!';
    static final int endChar = (int) '~';
    
    static String randomString(final int maxLength) {
      final int length = random.nextInt(maxLength + 1);
      return random.ints(length, startChar, endChar + 1)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
    }
    

提交回复
热议问题