Search code examples
javarandomalphanumeric

Generate a random Alphanumeric String without some characters


I want to generate a random Alphanumeric String. I want to exlude some characters from my string

l, i, o and the number 0

For the moment i have this code:

import org.apache.commons.lang.RandomStringUtils;
...
numberFile = RandomStringUtils.randomAlphanumeric( 5 );

Solution

  • Since you are using RandomStringUtils you might aswell use the designated RandomStringUtils#random method for that.

    public static String random(int count,
                                int start,
                                int end,
                                boolean letters,
                                boolean numbers,
                                char... chars)
    

    Parameters:
    count - the length of random string to create
    start - the position in set of chars to start at
    end - the position in set of chars to end before
    letters - only allow letters?
    numbers - only allow numbers?
    chars - the set of chars to choose randoms from. If null, then it will use the set of all chars.

    See the docs here.