io.github.whimthen.kits.RandomKit Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kits Show documentation
Show all versions of kits Show documentation
Easy to use java tool library.
package io.github.whimthen.kits;
import java.util.Random;
/**
* 随机字符工具类
*
* @project: kits
* @created: with IDEA
* @author: kits
* @Date: 2018 09 22 1:56 PM | September. Saturday
*/
public class RandomKit {
/**
* 随机获取字符串(包含0、o、O、1、I、i)
*
* @param length 长度
* @return 随机字符串
*/
public static String getString(int length) {
return getRandomStr(length, false, false, null);
}
/**
* 随机获取字符串(不包含0、o、O、1、I、i)
*
* @param length 长度
* @return 随机字符串
*/
public static String getStringRemove0oOIiLl(int length) {
return getRandomStr(length, false, true, null);
}
/**
* 随机获取字符串
*
* @param length 长度
* @param removeVal 需要去除的字符
* @return 随机字符串
*/
public static String getString(int length, String removeVal) {
return getRandomStr(length, false, false, removeVal);
}
/**
* 获取纯数字的验证码等
*
* @param length 长度
* @return 随机字符串
*/
public static String getNumber(int length) {
return getRandomStr(length, true, false, null);
}
/**
* 获取随机的字符串
*
* @param length 长度
* @param isNumber 是否为数字
* @param isRemove0oOIiLl 是否移除0oOIiLl
* @param removeVal 需要移除的字符串
* @return 随机字符串
*/
private static String getRandomStr(int length, boolean isNumber, boolean isRemove0oOIiLl, String removeVal) {
String resource = StringKit.getChars();
if (isNumber) {
resource = resource.substring(0, 10);
}
if (isRemove0oOIiLl) {
resource = StringKit.replaceAll(resource, "", "0|o|O|I|i|L|l");
}
if (StringKit.isNotNullOrEmpty(removeVal)) {
String removeRegex = String.join("|", StringKit.toCharList(removeVal));
resource = StringKit.replaceAll(resource, "", removeRegex);
}
StringBuilder randomStr = new StringBuilder();
Random random = new Random();
if (length > 0) {
for (int i = 0; i < length; i++) {
randomStr.append(resource.charAt(random.nextInt(resource.length())));
}
}
return randomStr.toString();
}
}