Created
December 24, 2017 05:52
-
-
Save zerda/cecb88954937f455115cd862f0421683 to your computer and use it in GitHub Desktop.
Create an random string in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.SecureRandom; | |
import java.util.Locale; | |
import java.util.Objects; | |
import java.util.Random; | |
/** | |
* Random String Generator. | |
* | |
* <code>new RandomString().nextString()</code> | |
* | |
* from https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string | |
*/ | |
class RandomString { | |
/** | |
* Generate a random string. | |
*/ | |
public String nextString() { | |
for (int idx = 0; idx < buf.length; ++idx) { | |
buf[idx] = symbols[random.nextInt(symbols.length)]; | |
} | |
return new String(buf); | |
} | |
public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
public static final String lower = upper.toLowerCase(Locale.ROOT); | |
public static final String digits = "0123456789"; | |
public static final String alphanum = upper + lower + digits; | |
private final Random random; | |
private final char[] symbols; | |
private final char[] buf; | |
public RandomString(int length, Random random, String symbols) { | |
if (length < 1) { | |
throw new IllegalArgumentException(); | |
} | |
if (symbols.length() < 2) { | |
throw new IllegalArgumentException(); | |
} | |
this.random = Objects.requireNonNull(random); | |
this.symbols = symbols.toCharArray(); | |
this.buf = new char[length]; | |
} | |
/** | |
* Create an alphanumeric string generator. | |
*/ | |
public RandomString(int length, Random random) { | |
this(length, random, alphanum); | |
} | |
/** | |
* Create an alphanumeric strings from a secure generator. | |
*/ | |
public RandomString(int length) { | |
this(length, new SecureRandom()); | |
} | |
/** | |
* Create session identifiers. | |
*/ | |
public RandomString() { | |
this(21); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment