1、第一个
package com.tigeriot.mqtt.util;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
public class StringUtil {
//
/**
* 将字符串的首字母转大写
*
* @param str
* 需要转换的字符串
* @return
*/
public static String captureName(String str) {
// 进行字母的ascii编码前移,效率要高于截取字符串进行转换的操作
char[] cs = str.toCharArray();
cs[0] -= 32;
return String.valueOf(cs);
}
/**
*
* @param str_source
* @param str_target
* @return
*/
public static boolean isEquString(String str_source, String str_target) {
boolean flag = false;
try {
if (str_target.equals(str_source)) {
flag = true;
}
} catch (Exception e) {
// TODO: handle exception
}
return flag;
}
///
public static String getNameDepart(String realname) {
try {
// String mobile = "15888888888";
String realname1 = null;
char[] r = realname.toCharArray();
// char[] m = mobile.toCharArray();
if (r.length == 1) {
realname1 = realname;
}
if (r.length == 2) {
realname1 = realname.replaceFirst(realname.substring(1), "*");
}
if (r.length > 2) {
realname1 = realname.replaceFirst(realname.substring(1, r.length - 1), "*");
}
// for (int i = 0; i < m.length; i++) {
// if (i > 2 && i < 7) {
// m[i] = '*';
// }
// }
// String mobile1 = String.valueOf(m);
// System.out.println(realname1);// 程*员
// System.out.println(mobile1);// 158****8888
return realname1;
} catch (Exception e) {
// TODO: handle exception
return realname;
}
}
///
public static String decodeby10(String str) {
StringBuffer out = new StringBuffer();
if (str == null || ("".equals(str)))
return "";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if ((chars[i] >= 19968 && chars[i] <= 40869) // 中日朝兼容形式的unicode编码范围:
// U+4E00——U+9FA5
|| (chars[i] >= 11904 && chars[i] <= 42191)// 中日朝兼容形式扩展
|| (chars[i] >= 63744 && chars[i] <= 64255)// 中日朝兼容形式扩展
|| (chars[i] >= 65072 && chars[i] <= 65103)// 中日朝兼容形式扩展
|| (chars[i] >= 65280 && chars[i] <= 65519)// 全角ASCII、全角中英文标点、半宽片假名、半宽平假名、半宽韩文字母的unicode编码范围:U+FF00——U+FFEF
|| (chars[i] >= 32 && chars[i] <= 126)// 半角字符的unicode编码范围:U+0020-U+007e
|| (chars[i] >= 12289 && chars[i] <= 12319)// 全角字符的unicode编码范围:U+3000——U+301F
) {
out.append(chars[i]);
}
}
String result = out.toString().trim();
result = result.replaceAll("\\?", "").replaceAll("\\*", "").replaceAll("<|>", "").replaceAll("\\|", "")
.replaceAll("/", "");
return result;
}
/**
*
* 判断为 16进制字符串
*
* @param str
* @return
*/
public static boolean isHexStr(String str) {
boolean isHexFlg = true;
int i = 0;
char c;
for (i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (!(((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'F')) || (c >= 'a') && (c <= 'f'))) {
isHexFlg = false;
}
}
return isHexFlg;
}
/*
* Convert byte[] to hex
* string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
*
* @param src byte[] data
*
* @return hex string
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*
* 2019年11月23日14:49:05
*
* 16进制 字符串 转 16进制数组
*/
public static byte[] HexStringToHexBytes(String hexString) {
try {
if (hexString == null || hexString.equals("")) {
return null;
}
if (!isHexStr(hexString)) {
throw new Exception( "不合法的十六进制!");
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
} catch (Exception e) {
// TODO: handle exception
// return null;
// e.printStackTrace();
System.out.println(e.getMessage());
}
return null;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
*
* 手机号码的加 *
*/
// public static String createProxyTokenByParentId(String parentId) {
//
// String token = parentId + "00000000000000000000";
//
// return token;
// }
/**
*
* 手机号码的加 *
*/
public static String getTel_PartContent(String tel) {
try {
// 括号表示组,被替换的部分$n表示第n组的内容
tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
return tel;
} catch (Exception e) {
// TODO: handle exception
return "***err***";
}
}
/**
* 将字符串以指定字符串切割后,分配到List中
*
* @param strValue-->输入字符串
* @return List
*/
public static List getTokenizerList(String strValue, String delim) {
List myList = new ArrayList();
if (strValue == null) {
return myList;
}
StringTokenizer stChat = new StringTokenizer(strValue, delim);
int iLength = stChat.countTokens();
for (int i = 0; i < iLength; i++) {
String strTemp = stChat.nextToken();
if (strTemp == null)
strTemp = "";
myList.add(strTemp);
}
return myList;
}
/**
*
* 将字节数组转为 HEX字符
*
* @param b
*/
public static void printHexString(byte[] b) {
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() + "");// + " "
}
System.out.println("");
}
/**
*
* 将字节转为 HEX字符
*
* @param b
*/
public static String getHexString(byte b) {
StringBuffer hex_str = new StringBuffer();
try {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hex_str.append(hex.toLowerCase());// + " "//转为小写
return hex_str.toString();
} catch (Exception e) {
return null;
}
}
/**
*
* 将字节数组转为 HEX字符
*
* @param b
*/
public static String getHexString(byte[] b) {
StringBuffer hex_str = new StringBuffer();
try {
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hex_str.append(hex.toLowerCase());// + " "//转为小写
}
return hex_str.toString();
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
/**
*
* 将字节数组转为 HEX字符
*
* @param hexString
*/
public static String[] getHexStringArr(String hexString) throws Exception {
try {
if (hexString == null || hexString.equals("")) {
return null;
}
if (!isHexStr(hexString)) {
throw new Exception("不合法的十六进制!");
}
String[] strList = new String[hexString.length()/2];
String [] temp = hexString.split("");
int index = 0;
for (int i = 0; i < temp.length; i+=2) {
strList[index] = temp[i] + temp[i+1];
index++;
}
return strList;
} catch (Exception e) {
// TODO: handle exception
// return null;
throw new Exception( "不合法的16进制!");
}
}
/**
*
* 截取字符串后几位
*/
public static String subStr(String str, int n) {
if (n < str.length()) {
return str.substring(str.length() - n, str.length());
} else {
return str;
}
}
/***
*
* 去除空格
*/
public static String StringTim(String str) {
try {
return str.replaceAll("\\s*", "").trim();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
*
* 抽取字符串里面的数字
*
* @param str
* @return
*/
public static String getNumStr(String str) {
str = str.trim();
String str2 = "";
if (str != null && !"".equals(str)) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
str2 += str.charAt(i);
}
}
}
return str2;
}
/**
*
* 判断字符串是否是全数字
*
* @param str
* @return
*/
public static boolean isNumStr(String str) {
str = str.trim();
boolean isNum = true;
if (str != null && !"".equals(str)) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
} else {
isNum = false;
}
}
} else {
isNum = false;
}
return isNum;
}
/**
* 字符串转化成为16进制字符串
*
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
/**
*
* long 转 4个 HEX
*
* @param i
* @return
*/
public static String getHex_4formLong(long i) {
String hex4 = "00000000" + Long.toHexString(i);
int length = hex4.length();
return hex4.substring(length - 8, length);
}
/**
*
* long 转 4个 HEX
*
* @param i
* @return
*/
public static String getHex_4formInt(int i) {
String hex4 = "00000000" + Integer.toHexString(i);
int length = hex4.length();
return hex4.substring(length - 8, length);
}
/**
*
* long 转 4个 HEX
*
* @param i
* @return
*/
public static String getHex_2formShort(short i) {
String hex4 = "00000000" + Integer.toHexString(i);
int length = hex4.length();
return hex4.substring(length - 4, length);
}
/**
*
* long 转 4个 HEX
*
* @param i
* @return
*/
public static String getHex_1formShort(short i) {
String hex4 = "00000000" + Integer.toHexString(i);
int length = hex4.length();
return hex4.substring(length - 2, length);
}
/**
*
* long 转 1个 HEX
*
* @param i
* @return
*/
public static String getHex_1formLong(byte i) {
String hex4 = "00000000" + Integer.toHexString(i);
int length = hex4.length();
return hex4.substring(length - 2, length);
}
/**
* 16进制直接转换成为字符串(无需Unicode解码)
*
* @param hexStr
* @return
*/
public static String hexStr_to_Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
//
/**
*
* 判断一个字符串是否为url
*
* @param str
* String 字符串
*
* @return boolean 是否为url
*
* @author peng1 chen
*
**/
public static boolean isURL(String str) {
// 转换为小写
str = str.toLowerCase();
String regex = "^((https|http|ftp|rtsp|mms|tcp)?://)" // https、http、ftp、rtsp、mms
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如:199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
return str.matches(regex);
}
/**
* ID数组json串转List
*
* @param bindUserIds_req
* @return
*/
public static List getStringListByJsonStr(String bindUserIds_req) {
List result = new ArrayList();
try {
if (bindUserIds_req != null) {
result = JSON.parseArray(bindUserIds_req, String.class);
}
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
/**
*
*
* @param args
*/
public static void main(String[] args) {
String str = "tcp://192.168.1.155";
System.out.println(isURL(str));
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
public static boolean isNotNullAndNotEmpty(String s) {
return !isNullOrEmpty(s);
}
// public static String getHex_2formInt(Integer num) {
// try {
// return StringUtil.getHexString(MathUtil.intToBytes2(num));
// }catch (Exception e){
//
// }
// return null;
// }
}
2、第二个
package com.tigeriot.mqtt.util;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.tigeriot.mqtt.common.CodeConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
@Slf4j
public class StringHexUtil {
/**
* 16进制字符串转字节数组
* @param hexStr
* @return
*/
public static byte[] hexToByte(String hexStr){
if(StringUtils.isEmpty(hexStr) ||!isHexStr(hexStr)){
//判断失败
return null;
}
return stringHexToBytes(hexStr);
}
/**
* 实现字节数组转16进制字符串
* @param bytes
* @return
*/
public static String byteToHex(byte[] bytes){
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
* 判断是否合格16进制数
* @param hexStr
* @return
*/
public static boolean isHexStr(String hexStr){
String []s = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","a","b","c","d","e","f"};
List list = Arrays.asList(s);
char [] chars = hexStr.toCharArray();
for (char c : chars) {
if(!list.contains(String.valueOf(c))){
return false;
}
}
return true;
}
/**
* 实现 16进制 字符串转字节数组
* @param str
* @return
*/
public static byte[] stringHexToBytes(String str){
char[] hexChars = str.toCharArray();
byte[] bytes = new byte[hexChars.length / 2];
for (int i = 0; i < bytes.length; i++) {
int highNibble = Character.digit(hexChars[i * 2], 16);
int lowNibble = Character.digit(hexChars[i * 2 + 1], 16);
bytes[i] = (byte) ((highNibble << 4) | lowNibble);
}
return bytes;
}
/**
* 判断字符串是否 为空串 为null 为空格
* @param str
* @return
*/
public static boolean isNotBlank(String str) {
return str != null && !str.isEmpty() && !str.trim().isEmpty();
}
/**
* 验证 clientID 是否合法
* @param clientID
* @return
*/
public static RV validateClientID(String clientID){
if (!StringHexUtil.isNotBlank(clientID)){
log.info("您的clientID不能为空格,空串,null:"+clientID);
return RV.error(CodeConst.FAIL,"您的ClientID为空或空串",null);
} else if (clientID.length()!=15) {
log.info("您的clientID长度不为15:"+clientID);
return RV.error(CodeConst.FAIL,"您的clientID长度不为15",null);
} else if (!isNumeric(clientID)) {
log.info("您的clientID不是数字:"+clientID);
return RV.error(CodeConst.FAIL,"您的clientID不是数字",null);
} else {
return RV.ok(CodeConst.SUCCESS,"验证通过",null);
}
}
/**
* 生成 n 位随机 0-9的数
* @param length
* @return
*/
public static String generateRandomNumber(int length) {
Random random = new Random();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int digit = random.nextInt(10); // 生成0-9的随机数字
sb.append(digit);
}
return sb.toString();
}
//随机20位字符串
private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITS = "0123456789";
private static final String ALL_CHARACTERS = LOWERCASE_CHARACTERS + UPPERCASE_CHARACTERS + DIGITS;
private static final SecureRandom RANDOM = new SecureRandom();
/**
* 随机生成20位 包含大小写字母与数字的字符串
* @param length
* @return
*/
public static String generateRandomString(int length) {
StringBuilder randomString = new StringBuilder(length);
// 确保至少包含一个小写字母、一个大写字母和一个数字字符
randomString.append(LOWERCASE_CHARACTERS.charAt(RANDOM.nextInt(LOWERCASE_CHARACTERS.length())));
randomString.append(UPPERCASE_CHARACTERS.charAt(RANDOM.nextInt(UPPERCASE_CHARACTERS.length())));
randomString.append(DIGITS.charAt(RANDOM.nextInt(DIGITS.length())));
// 生成剩余的字符
for (int i = 3; i < length; i++) {
randomString.append(ALL_CHARACTERS.charAt(RANDOM.nextInt(ALL_CHARACTERS.length())));
}
// 洗牌字符,使其顺序随机
return shuffleString(randomString.toString());
}
/**
* 函数用于洗牌字符串中的字符
* @param input
* @return
*/
private static String shuffleString(String input) {
char[] characters = input.toCharArray();
for (int i = characters.length - 1; i > 0; i--) {
int randomIndex = RANDOM.nextInt(i + 1);
char temp = characters[i];
characters[i] = characters[randomIndex];
characters[randomIndex] = temp;
}
return new String(characters);
}
/**
* 验证字符串是不是纯数字
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (str == null || str.length() == 0) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 将字符串实现SHA256加密算法
* @param str
*/
public static String strToSha256(String str){
return DigestUtil.sha256Hex(str);
}
public static void main(String[] args) {
System.out.println(generateRandomString(20));
}
}
需要导入依赖
cn.hutool
hutool-all
5.8.18