Java: Generate Random String

Categories: Java; Tagged with: ; @ December 22nd, 2014 23:04

Solution:
1). generate random string using java.util.Random; or
2). Use Apache commons lang;

   public void testRandomString() {
        System.out.println("RandomStringGenerator.getRandomString(5): " + RandomStringGenerator.getRandomString(5));

        System.out.println("RandomStringUtils.random(5): " + RandomStringUtils.random(5));
        System.out.println("RandomStringUtils.randomAlphabetic(5): " + RandomStringUtils.randomAlphabetic(5));
        System.out.println("RandomStringUtils.randomNumeric(5): " + RandomStringUtils.randomNumeric(5));
    }

output:


RandomStringGenerator.getRandomString(5): r2irv
RandomStringUtils.random(5): 㩩ﻰ뒛ţ䍋
RandomStringUtils.randomAlphabetic(5): Nhnfe
RandomStringUtils.randomNumeric(5): 51685

1. Random String Generator:

package com.liguoliang.java.utils;

import java.util.Random;

/**
 * Created by Guoliang, Li on 12/22/2014.
 */
public class RandomStringGenerator {

    private static char[] repo;
    static {
        StringBuilder tmp = new StringBuilder();
        for (char ch = '0'; ch <= '9'; ++ch)
            tmp.append(ch);
        for (char ch = 'a'; ch <= 'z'; ++ch)
            tmp.append(ch);
        repo = tmp.toString().toCharArray();
    }

    public static String getRandomString(int length) {
        char[] buf = new char[length];
        Random random = new Random();

        if (length < 1) {
            throw new IllegalArgumentException("length < 1: " + length);
        }

        for (int i = 0; i < buf.length; i++) {
            buf[i] = repo[random.nextInt(repo.length)];
        }
        return new String(buf);
    }
}

Apache commons lang:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.