Получить рандомную строку java

Как в Java сгенерировать случайную строку

В этом руководстве узнаем, как генерировать случайную строку в Java, сначала используя стандартные библиотеки Java, затем используя вариант Java 8 и, наконец, используя библиотеку Apache Commons Lang.

Генерация случайной строки неограниченного размера с помощью Java

Начнем с простого и сгенерируем случайную строку, ограниченную 7 символами:

@Test public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() < byte[] array = new byte[7]; // длина ограничена 7 new Random().nextBytes(array); String generatedString = new String(array, Charset.forName("UTF-8")); System.out.println(generatedString); >

Имейте в виду, что новая строка не будет буквенно-цифровой.

Генерация случайной строки ограниченного размера с помощью Java

Посмотрим на создание более ограниченной случайной строки.

Сгенерируем случайную строку, используя строчные буквы алфавита и заданную длину:

@Test public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() < int leftLimit = 97; // буква 'a' int rightLimit = 122; // буква '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); >

4. Генерация случайной строки из букв с помощью Java 8

Читайте также:  Birthday Reminders for August

Воспользуемся Random.ints, добавленным в JDK 8, для генерации алфавитной строки:

@Test public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() < int leftLimit = 97; // буква 'a' int rightLimit = 122; // буква '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); >

Генерация случайной буквенно-цифровой строки с помощью Java 8

Затем можно расширить набор символов, чтобы получить буквенно-цифровую строку:

@Test public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() < int leftLimit = 48; // цифра '0' int rightLimit = 122; // буква 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i ->(i = 65) && (i = 97)) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString); >

Мы использовали описанный выше метод фильтрации, чтобы пропустить символы Unicode между 65 и 90, чтобы избежать появления символов вне допустимого диапазона.

Генерация ограниченной случайной строки с помощью Apache Commons Lang

Библиотека Commons Lang от Apache очень помогает при генерации случайных строк. Посмотрим на создание ограниченной строки, используя только буквы:

@Test public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect()

Таким образом, вместо всего низкоуровневого кода в примере с Java здесь используется простой однострочный код.

Генерация алфавитной строки с помощью Apache Commons Lang

Вот еще один очень простой пример, на этот раз ограниченная строка только с буквенными символами, но без передачи логических флагов в API:

@Test public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect()

Генерация буквенно-цифровой строки с помощью Apache Commons Lang

Наконец, получим ту же самая случайную ограниченную строку, но на этот раз числовую:

@Test public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect()

Мы создали ограниченные и неограниченные строки либо с помощью Java, либо с Java 8, либо с библиотекой Apache Commons.

Заключение

Благодаря различным способам реализации мы смогли сгенерировать ограниченные и неограниченные строки, используя обычную Java, вариант Java 8 или библиотеку Apache Commons.

В этих примерах использовали java.util.Random, но стоит упомянуть, что она не является криптографически безопасной. Рассмотрите возможность использования java.security.SecureRandom вместо приложений, чувствительных к безопасности.

Реализацию всех этих примеров и фрагментов можно найти в проекте GitHub. Это проект на основе Maven, поэтому его легко импортировать и запускать.

Источник

Java generate random string

Method 1 : Using UUID
java.util.UUID class can be used to get a random string. Its static randomUUID method acts as a random alphanumeric generator and returns a String of 32 characters.
If you want a string of a fixed length or shorter than 32 characters, you can use substring method of java.lang.String .
Example,

import java.util.UUID; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingUUID(); System.out.println("Random string is: " + randomString); System.out.println("Random string of 8 characters is: " + randomString.substring(0, 8)); >static String usingUUID() < UUID randomUUID = UUID.randomUUID(); return randomUUID.toString().replaceAll("-", ""); >>

Note that the string generated by randomUUID method contains ““. Above example removes those by replacing them with empty string.
Output of above program will be

Random string is: 923ed6ec4d04452eaf258ec8a4391a0f
Random string of 8 characters is: 923ed6ec

Method 2 : Using Math class
Following algorithm can be used to generate a random alphanumeric string of fixed length using this method.

  1. Initialize an empty string to hold the result.
  2. Create a combination of upper and lower case alphabets and numerals to create a super set of characters.
  3. Initiate a loop for with count equal to the length of random string required.
  4. In every iteration, generate a random number between 0 and the length of super set.
  5. Extract the character from the string in Step 2 at the index of number generated in Step 4 and add it to the string in Step 1.
    After the loop completes, string in Step 1 will be a random string.
import java.util.Math; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingMath(); System.out.println("Random string is: " + randomString); >static String usingMath() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = (int)(Math.random() * allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >

Output of above program executed thrice is

Random string is: kqNG2SYHeF
Random string is: lCppqqUg8P
Random string is: GGiFiEP5Dz

This approach gives you more control over the characters that need to be included in the random string.

For example, if you do not want numbers, then remove them from the super set. If you want special characters, then add a set of special characters in the super set.

Method 3 : Using Random class
This method follows a similar approach as the above method in that a super set of all the characters is created, a random index is generated and character at that index is used to create the final string.
But this approach uses java.util.Random class to generate a random index. Example,

import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingRandom(); System.out.println("Random string is: " + randomString); >static String usingRandom() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = random.nextInt(allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >

You can also use java.util.SecureRandom class to generate a random integer. It is a subclass of java.util.Random .
Output of three executions of above program is

Random string is: TycOBOxITs
Random string is: 7LLWVbg0ps
Random string is: p6VyqdO6bT

Method 4 : Using RandomStringUtils
Apache Commons Lang library has an org.apache.commons.lang.RandomStringUtils class with methods to generate random string of a fixed length.

It has methods that can generate a random string of only alphabets( randomAlphabetic ), numbers( randomNumeric ) or both( randomAlphanumeric ).

All these methods accept an integer argument which represents the length of the string that they will generate.
Below is an example.

import org.apache.commons.lang.RandomStringUtils; public class RandomStringGenerator < public static void main(String[] args) < // generate a random string of 10 alphabets String randomString = RandomStringUtils.randomAlphabetic(10); System.out.println("Random string of 10 alphabets: " + randomString); randomString = RandomStringUtils.randomNumeric(10); System.out.println("Random string of 10 numbers: " + randomString); randomString = RandomStringUtils.randomAlphanumeric(10); System.out.println("Random string of 10 alphanumeric characters: " + randomString); >>

Output of above program is

Random string of 10 alphabets: OEfadIYfFm
Random string of 10 numbers: 1639479195
Random string of 10 alphanumeric characters: wTQRMXrNY9

This class also has a method random() that takes an integer which is the length of the string to be generated and a char array. Random string generated consists of only characters from this array.

Apache Commons Lang can be included into your project by adding the below dependency as per the build tool.

 org.apache.commons commons-lang3 3.9 
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

Method 5 : Using java 8 Stream
With Java 8 streams , we can generate a random alphanumeric string of fixed length.
The idea is to generate a stream of random numbers between ASCII values of 0-9, a-z and A-Z, convert each integer generated into corresponding character and append this character to a StringBuffer.

Example code is given below

import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) throws IOException < Random r = new Random(); String s = r.ints(48, 123) .filter(num ->(num < 58 || num >64) && (num < 91 || num >96)) .limit(10) .mapToObj(c -> (char) c).collect(StringBuffer::new, StringBuffer::append, StringBuffer::append) .toString(); System.out.println('Random alphanumeric string is: " + s); > >

java.util.Random class has a new method ints() added in java 8.

ints() takes two integer arguments and generates a stream of integers between those two integers with start inclusive and end exclusive.
This stream is filtered with filter() method to include ASCII values of only 0-9, a-z and A-Z.
If you want other characters as well, then filter() is not required.

limit() is required to generate a random string of 10 characters. Without limit() , the stream will keep on generating integers infinitely.

mapToObj() converts integer value to corresponding character.
Both filter() and mapToObj() accept a functional interface as argument and so we can pass a Lambda expression .

Finally, collect() is used to collect the values generated by the stream into a StringBuffer using its append() method.
This StringBuffer is converted to a string with toString() method.

Range of integers provided to ints() is chosen according to ASCII values of numbers and alphabets. You can choose these according to the characters that need to be included in the string to generate.

Multiple executions of this program generate following output

Random alphanumeric string is: tCh5OTWY4v
Random alphanumeric string is: pHLjsd0ts4
Random alphanumeric string is: L82EvKMfsm

That is all on different ways to generate a random string in java. Hope the article was helpful !!

Источник

Create random String in Java example

Create random String in Java example shows how to create random string of a specified length in Java. The example also shows how to create random alphanumeric string, random numeric string or random alphabetic string in Java.

How to create a random string of the specified length in Java?

There are several ways in which you can create a random string in Java as given below.

1) Using the Random and String classes

We can create a random string of specified length using the java.util.Random class as given below.

We kept all the allowed characters in a String for later reference and took one random character from it and appended it to the StringBuilder object. When we had required string length, we converted StringBuilder to String and returned it.

You can change the String containing allowed characters according to your needs. You can also change the string required length to generate a random string of specified characters.

Note: Please note that the above solution uses java.util.Random class. If you want a secure solution change the Radom with SecureRandom class.

If you are using Java 1.4 or earlier version, use the StringBuffer class instead of the StringBuilder class.

2) Using the SecureRandom and BigInteger classes

The BigInteger class can be used to generate random strings by using below given constructor.

This constructor creates randomly generated non-negative BigInteger in the range of 0 to 2^bits – 1. Here is the example program to generate random string using BigInteger and SecureRandom classes.

Источник

Java – generate random String

In this tutorial, we will see how to generate random String in java.
There are many ways to generate random String.Let’s explore some of ways to generate random String.

Using simple java code with Random

You can use SecureRandom class to generate random String for you.
Let’s understand with the help of example.

System . out . println ( «Generating String of length 10: » + rsgm . generateRandomStringUsingSecureRandom ( 10 ) ) ;

System . out . println ( «Generating String of length 10: » + rsgm . generateRandomStringUsingSecureRandom ( 10 ) ) ;

System . out . println ( «Generating String of length 10: » + rsgm . generateRandomStringUsingSecureRandom ( 10 ) ) ;

System . out . println ( «Generating String of length 8: » + rsgm . generateRandomStringUsingSecureRandom ( 8 ) ) ;

System . out . println ( «Generating String of length 8: » + rsgm . generateRandomStringUsingSecureRandom ( 8 ) ) ;

System . out . println ( «Generating String of length 8: » + rsgm . generateRandomStringUsingSecureRandom ( 8 ) ) ;

System . out . println ( «Generating String of length 7: » + rsgm . generateRandomStringUsingSecureRandom ( 7 ) ) ;

System . out . println ( «Generating String of length 7: » + rsgm . generateRandomStringUsingSecureRandom ( 7 ) ) ;

System . out . println ( «Generating String of length 7: » + rsgm . generateRandomStringUsingSecureRandom ( 7 ) ) ;

Generating String of length 10: Hz0hHRcO6X
Generating String of length 10: wSnjx6HNlv
Generating String of length 10: 4Wg9Iww0Is
Generating String of length 8: EdJmSrfC
Generating String of length 8: dAifHyQG
Generating String of length 8: HNnxieWg
Generating String of length 7: hQrqQ2L
Generating String of length 7: 0BWBtYI
Generating String of length 7: 3WStHON

Using Apache Common lang

You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.

Create AlphaNumericString

You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.

Источник

Оцените статью