@Testpublic void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { byte[] array = new byte[7]; // length is bounded by 7 new Random().nextBytes(array); String generatedString = new String(array, Charset.forName("UTF-8")); System.out.println(generatedString);}
接下来–让我们看一下如何创建一个更受限的随机字符串;我们将使用小写字母字母和设置的长度生成一个随机字符串:
@Testpublic void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { int leftLimit = 97; // letter 'a' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } String generatedString = buffer.toString(); System.out.println(generatedString);}
现在,让我们使用在JDK 8中添加的Random.ints生成字母字符串:
@Testpublic void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() { int leftLimit = 97; // letter 'a' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString);}
然后我们可以扩展字符集以获得字母数字字符串:
@Testpublic void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString);}
请注意,上面使用了filter方法,以排除65至90之间的Unicode字符-避免超出范围的字符。
Apache的Commons Lang库在随机字符串生成方面有很大帮助。让我们看一下仅使用字母生成有界字符串:
@Testpublic void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { int length = 10; boolean useLetters = true; boolean useNumbers = false; String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); System.out.println(generatedString);}
另一个非常简单的示例–这次是一个只包含字母字符但没有将布尔标志传递给API的有界字符串:
@Testpublic void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { String generatedString = RandomStringUtils.randomAlphabetic(10); System.out.println(generatedString);}
最后-相同的随机有界String,但是这次-数字:
@Testpublic void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { String generatedString = RandomStringUtils.randomAlphanumeric(10); System.out.println(generatedString);}
有了它,就可以使用纯Java,Java 8变体或Apache Commons Library创建有界和无界的字符串。
通过不同的实现方法,我们能够使用纯Java,Java 8变体或Apache Commons Library生成绑定和未绑定的字符串。
在这些Java示例中,我们使用了java.util.Random,但值得一提的是,它不是加密安全的。考虑对安全敏感的应用程序改用java.security.SecureRandom。
联系客服