1 16 package org.apache.commons.lang; 17 18 import java.util.Random ; 19 31 public class RandomStringUtils { 32 33 38 private static final Random RANDOM = new Random (); 39 40 48 public RandomStringUtils() { 49 } 50 51 62 public static String random(int count) { 63 return random(count, false, false); 64 } 65 66 76 public static String randomAscii(int count) { 77 return random(count, 32, 127, false, false); 78 } 79 80 90 public static String randomAlphabetic(int count) { 91 return random(count, true, false); 92 } 93 94 104 public static String randomAlphanumeric(int count) { 105 return random(count, true, true); 106 } 107 108 118 public static String randomNumeric(int count) { 119 return random(count, false, true); 120 } 121 122 136 public static String random(int count, boolean letters, boolean numbers) { 137 return random(count, 0, 0, letters, numbers); 138 } 139 140 156 public static String random(int count, int start, int end, boolean letters, boolean numbers) { 157 return random(count, start, end, letters, numbers, null, RANDOM); 158 } 159 160 180 public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) { 181 return random(count, start, end, letters, numbers, chars, RANDOM); 182 } 183 184 217 public static String random(int count, int start, int end, boolean letters, boolean numbers, 218 char[] chars, Random random) { 219 if (count == 0) { 220 return ""; 221 } else if (count < 0) { 222 throw new IllegalArgumentException ("Requested random string length " + count + " is less than 0."); 223 } 224 if ((start == 0) && (end == 0)) { 225 end = 'z' + 1; 226 start = ' '; 227 if (!letters && !numbers) { 228 start = 0; 229 end = Integer.MAX_VALUE; 230 } 231 } 232 233 StringBuffer buffer = new StringBuffer (); 234 int gap = end - start; 235 236 while (count-- != 0) { 237 char ch; 238 if (chars == null) { 239 ch = (char) (random.nextInt(gap) + start); 240 } else { 241 ch = chars[random.nextInt(gap) + start]; 242 } 243 if ((letters && numbers && Character.isLetterOrDigit(ch)) 244 || (letters && Character.isLetter(ch)) 245 || (numbers && Character.isDigit(ch)) 246 || (!letters && !numbers)) { 247 buffer.append(ch); 248 } else { 249 count++; 250 } 251 } 252 return buffer.toString(); 253 } 254 255 268 public static String random(int count, String chars) { 269 if (chars == null) { 270 return random(count, 0, 0, false, false, null, RANDOM); 271 } 272 return random(count, chars.toCharArray()); 273 } 274 275 287 public static String random(int count, char[] chars) { 288 if (chars == null) { 289 return random(count, 0, 0, false, false, null, RANDOM); 290 } 291 return random(count, 0, chars.length, false, false, chars, RANDOM); 292 } 293 294 } 295 | Popular Tags |