Monday, February 15, 2016

Generate a random String of specified length in Java

Sure you can write a short piece of code of your own to do this, but apache's common library makes it just a one line task.  Furthurmore, the library is so widely used, it's maybe already in your class path involved by other third party library even you haven't noticed that. 

In case you don't have it in your class path, add this to you maven pom.xml

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.0</version>
</dependency>

Here are the ways to create the most used random String, include random ASCII, random letters, random digits and random letter+digits. Use RandomStringUtils's static methods to get what you need.

  int count = 6; // length of the generated String
  
  // from all ASCII code [32-126] 
  System.out.println(RandomStringUtils.randomAscii(count));  // ex. L\=u8_
  
  // from [A-Z,a-z]
  System.out.println(RandomStringUtils.randomAlphabetic(count)); // ex. TxTbYm
  
  // from [0-9]
  System.out.println(RandomStringUtils.randomNumeric(count));  // ex. 953626
  
  // from [A-Z,a-z,0-9]
  System.out.println(RandomStringUtils.randomAlphanumeric(count));//ex. Wuycb5

0 comments:

Post a Comment

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List