Does anybody know of a good way to generate a random String of specified length and characters in Java.
For example 'length' could be 5 and 'possibleChars' could be 'a,b,c,1,2,3,!'.
So
c!a1b is valid
BUT
cba16 is not.
I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...
Any ideas?
You want something like this?
Random r=new Random();
char[] possibleChars="abc123!".toCharArray();
int length=5;
char[] newPassword=new char[length];
for (int i=0; i<length;i++)
newPassword[i]=possibleChars[r.nextInt(possibleChars.length)];
System.out.println(new String(newPassword));
The code to do this is pretty short. Have a char[] or String with N legal chars, and, length times, pick a random number R between 0 and N-1, use R to pick a character to append to your generated String.
I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...
It is not that common, and the detailed requirements are different each time. Besides, the code is simple to the point of being trivial. (Modulo the concerns below ... which are really about the requirements rather than the solution.)
In short, it is quicker to write your own method than to go looking for an existing library method that does this.
When you use a scheme that involves random numbers, you need to be aware of the possibility that you will get collisions; i.e. that the method will generate the same random string on more than one occasion. You can mitigate this by using a longer string, but that only works to a certain point ... depending on your random number generator. (Typical random number generators are actually pseudo-random number generators, and produce a sequence of numbers that eventually cycle around. And even with a perfect random number generator there is a finite probability of repeats over a short sequence.)
In fact, this is another reason why a "one size fits all" solution to your problem is not a good idea.
If this is for real security, as opposed to homework or a programming exercise, then use SecureRandom, not Random.
Read the Diceware website for a lot of very good ideas on the random generation of passwords and other things.