Possible Duplicate:
How to generate a random alpha-numeric string in Java
I want to write a code that build random string by Specified length . how can do it?
Possible Duplicate:
How to generate a random alpha-numeric string in Java
I want to write a code that build random string by Specified length . how can do it?
Here are the examples to generate two types of strings.
import java.security.SecureRandom;
import java.math.BigInteger;
public final class SessionIdentifierGenerator
{
private SecureRandom random = new SecureRandom();
public String nextSessionId()
{
return new BigInteger(130, random).toString(32);
}
}
OUTPUT: ponhbh78cqjahls5flbdf4dlu4
Refer here
String uuid = UUID.randomUUID().toString();
System.out.println("uuid = " + uuid);
OUTPUT: 281211f4-c1d7-457a-9758-555041a5ff97
Refer here
Well, you first write a function that will give you a random character meeting your requirements, then wrap that up in a for
loop based on the desired length.
The following program gives one way of doing this, using a constant pool of characters and a random number generator:
import java.util.Random;
public class testprog {
private static final char[] pool = {
'a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z'};
private Random rnd;
public testprog () { rnd = new Random(); }
public char getChar() { return pool[rnd.nextInt(pool.length)]; }
public String getStr(int sz) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sz; i++)
sb.append(getChar());
return new String(sb);
}
public static void main(String[] args) {
testprog tp = new testprog ();
for (int i = 0; i < 10; i++)
System.out.println (tp.getStr(i+5));
}
}
On one particular run, that gives me:
hgtbf
xismun
cfdnazi
cmpczbal
vhhxwjzbx
gfjxgihqhh
yjgiwnftcnv
ognwcvjucdnm
hxiyqjyfkqenq
jwmncfsrynuwed
Now, you can adjust the pool of characters if you want it from a different character set, you can even adjust the skewing towards specific characters by changing how often they occur in the array (more e
characters than z
, for example).
But that should be a good start for what you're trying to do.