ArticleDirectory
- Method 1
- Method 2
- Comparison of advantages and disadvantages
In SQL testing or other cases, we often need to obtain random strings.
Here we provide two methods to obtain random strings.
Method 1 parameter is the length of the string.
/** Generate a random string */public static string randomstring (INT length) {string STR = "random"; random = new random (); stringbuffer Buf = new stringbuffer (); For (INT I = 0; I <length; I ++) {int num = random. nextint (62); Buf. append (Str. charat (Num);} return Buf. tostring ();}
Method 2 [note] is only applicable to JDK 1.7. The parameter is also the length of the string.
/** Generate a random string, applicable to JDK 1.7 */public static string random (INT length) {stringbuilder builder = new stringbuilder (length); For (INT I = 0; I <length; I ++) {builder. append (char) (threadlocalrandom. current (). nextint (33,128);} return builder. tostring ();}
Comparison of advantages and disadvantages method 1 can generate characters that can appear in a given string, but only these characters can appear. The method of method 2 is simple and has many types of Characters in the generated random string. The disadvantage is that it is only applicable to JDK 1.7.