JAVA工具類(10)--- 隨機生成字串工具類randomUtil
阿新 • • 發佈:2019-01-10
package com.gcloud.common;
import java.util.Random;
/**
* 隨機數、隨即字串工具
* Created by charlin on 2017/9/9.
*/
public class RandomUtil {
public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
public static final String numberChar = "0123456789";
/**
* 產生len長度的隨機字串
* @param len
* @return
*/
public static String generateStr(int len){
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i <len ; i++) {
sb.append(allChar.charAt(random.nextInt(allChar.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純字母字串(只包含大小寫字母)
* @param length 隨機字串長度
* @return 隨機字串
*/
public static String generateMixStr(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(letterChar.charAt(random.nextInt(letterChar.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純大寫字母字串(只包含大小寫字母)
* @param length 隨機字串長度
* @return 隨機字串
*/
public static String generateLowerStr(int length) {
return generateMixStr(length).toLowerCase();
}
/**
* 返回一個定長的隨機純小寫字母字串(只包含大小寫字母)
* @param length 隨機字串長度
* @return 隨機字串
*/
public static String generateUpperStr(int length) {
return generateMixStr(length).toUpperCase();
}
/**
* 生成一個定長的純0字串
* @param length 字串長度
* @return 純0字串
*/
public static String generateZeroStr(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根據數字生成一個定長的字串,長度不夠前面補0
* @param num 數字
* @param fixdlenth 字串長度
* @return 定長的字串
*/
public static String toFixedLengthStr(long num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroStr(fixdlenth - strNum.length()));
} else {
throw new RuntimeException("將數字" + num + "轉化為長度為" + fixdlenth + "的字串發生異常!");
}
sb.append(strNum);
return sb.toString();
}
public static void main(String[] args) {
System.out.println(toFixedLengthStr(10, 4));
}
}
———————————————————————
(java 架構師全套教程,共760G, 讓你從零到架構師,每月輕鬆拿3萬)
有需求者請進站檢視,非誠勿擾
https://item.taobao.com/item.htm?spm=686.1000925.0.0.4a155084hc8wek&id=555888526201
01.高階架構師四十二個階段高
02.Java高階系統培訓架構課程148課時
03.Java高階網際網路架構師課程
04.Java網際網路架構Netty、Nio、Mina等-視訊教程
05.Java高階架構設計2016整理-視訊教程
06.架構師基礎、高階片
07.Java架構師必修linux運維繫列課程
08.Java高階系統培訓架構課程116課時
(送:hadoop系列教程,java設計模式與資料結構, Spring Cloud微服務, SpringBoot入門)
——————————————————————–