java - Comment générer une chaîne alphanumérique aléatoire

Mots clés : javastringrandomalphanumericjava

meilleur 5 Réponses java - Comment générer une chaîne alphanumérique aléatoire

vote vote

90

public class RandomString {      /**      * Generate a random string.      */     public String nextString() {         for (int idx = 0; idx < buf.length; ++idx)             buf[idx] = symbols[random.nextInt(symbols.length)];         return new String(buf);     }      public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";      public static final String lower = upper.toLowerCase(Locale.ROOT);      public static final String digits = "0123456789";      public static final String alphanum = upper + lower + digits;      private final Random random;      private final char[] symbols;      private final char[] buf;      public RandomString(int length, Random random, String symbols) {         if (length < 1) throw new IllegalArgumentException();         if (symbols.length() < 2) throw new IllegalArgumentException();         this.random = Objects.requireNonNull(random);         this.symbols = symbols.toCharArray();         this.buf = new char[length];     }      /**      * Create an alphanumeric string generator.      */     public RandomString(int length, Random random) {         this(length, random, alphanum);     }      /**      * Create an alphanumeric strings from a secure generator.      */     public RandomString(int length) {         this(length, new SecureRandom());     }      /**      * Create session identifiers.      */     public RandomString() {         this(21);     }  } 
RandomString gen = new RandomString(8, ThreadLocalRandom.current()); 
RandomString session = new RandomString(); 
String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx"; RandomString tickets = new RandomString(23, new SecureRandom(), easy); 
vote vote

87

import java.util.UUID;  public class randomStringGenerator {     public static void main(String[] args) {         System.out.println(generateString());     }      public static String generateString() {         String uuid = UUID.randomUUID().toString();         return "uuid = " + uuid;     } } 
uuid = 2d7428a6-b58c-4008-8575-f05549f16316 
vote vote

80

static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static SecureRandom rnd = new SecureRandom();  String randomString(int len){    StringBuilder sb = new StringBuilder(len);    for(int i = 0; i < len; i++)       sb.append(AB.charAt(rnd.nextInt(AB.length())));    return sb.toString(); } 
vote vote

67

RandomStringGenerator randomStringGenerator =         new RandomStringGenerator.Builder()                 .withinRange('0', 'z')                 .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)                 .build(); randomStringGenerator.generate(12); // toUpperCase() if you want 
vote vote

51

RandomStringUtils.randomAlphanumeric(20).toUpperCase(); 

Questions similaires