Return a string of random alphanumeric characters. - Java java.lang

Java examples for java.lang:String Random

Description

Return a string of random alphanumeric characters.

Demo Code


//package com.java2s;

import java.security.SecureRandom;

public class Main {
    public static void main(String[] argv) {
        int len = 42;
        System.out.println(randomString(len));
    }//from w  w  w  .  j ava2s. co m

    private static SecureRandom random = new SecureRandom();
    private static final char[] RANDOM_CHARACTER_STRING_SET = { 'a', 'b',
            'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C',
            'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'P', 'Q',
            'R', 'S', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5',
            '6', '7', '8', '9', };

    /**
     * Return a string of random alphanumeric characters.  Characters 0, O, l
     * and 1 are excluded, to ensure if the string is written down, there is no
     * confusion over these characters.
     *
     * @param len Length of the random string.
     * @return A string of random characters.
     */
    public static String randomString(int len) {

        long r = random.nextLong();
        if (r < 0) {
            r = -r;
        }

        // random chance to reseed
        if (r % 100000L == 1L) {
            random.setSeed(random.generateSeed(8));
        }

        StringBuffer str = new StringBuffer();
        for (int i = 0; i < len; i++) {
            int n = random.nextInt(RANDOM_CHARACTER_STRING_SET.length);
            str.append(RANDOM_CHARACTER_STRING_SET[n]);
        }

        return str.toString();
    }
}

Related Tutorials