Generate random String among 0-9 a-z A-Z - Android java.util

Android examples for java.util:Random String

Description

Generate random String among 0-9 a-z A-Z

Demo Code

import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

public class Main{

    public static String randomString(int length) {
        Random randGen = null;//from  w ww  .j a  va2  s  .co m
        char[] numbersAndLetters = null;
        if (length < 1) {
            return null;
        }

        if (randGen == null) {
            randGen = new Random();
            numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
                    + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
        }
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
        }
        return new String(randBuffer);
    }

}

Related Tutorials