编写工具模块

文章目录

    • 1.新建模块
        • 1.新建模块sun-common-tool
        • 2.sun-dependencies指定依赖
        • 3.sun-common统一管理sun-common-tool子模块
        • 4.sun-common-tool的pom.xml
        • 5.清除掉创建模块时默认sun-frame对sun-common-tool进行管理
    • 2.常用工具类
        • 1.DateUtils.java
        • 2.EncodeUtils.java
        • 3.IpUtils.java
        • 4.LetterUtils.java
        • 5.MaskUtils.java
        • 6.Md5Utils.java
        • 7.PinYin4jUtils.java
        • 8.PropertiesUtils.java
        • 9.SimpleDateFormatUtils.java
        • 10.SpringContextUtils.java
        • 11.ThreadPoolUtils.java
        • 12.UuidUtils.java

1.新建模块

1.新建模块sun-common-tool
2.sun-dependencies指定依赖
            <freemarker.version>2.3.30</freemarker.version><pinyin4j.version>2.5.0</pinyin4j.version><commons.lang3.version>3.8</commons.lang3.version><!-- freemarker --><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>${freemarker.version}</version></dependency><!-- pinyin4j --><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>${pinyin4j.version}</version></dependency><!-- commons-lang3 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons.lang3.version}</version></dependency>
3.sun-common统一管理sun-common-tool子模块

CleanShot 2024-07-21 at 14.38.40@2x

4.sun-common-tool的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- 继承父模块的版本和通用依赖 --><parent><groupId>com.sunxiansheng</groupId><artifactId>sun-common</artifactId><version>1.0-SNAPSHOT</version></parent><artifactId>sun-common-tool</artifactId><!-- 子模块的version,如果不写就默认跟父模块的一样 --><version>${children.version}</version><!-- 自定义依赖,无需版本号 --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency></dependencies></project>
5.清除掉创建模块时默认sun-frame对sun-common-tool进行管理

2.常用工具类

1.DateUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.text.SimpleDateFormat;
import java.util.*;/*** 日期工具类* 提供了常用的日期操作方法,例如获取某日期的开始和结束时间,计算两个日期之间的天数等。*/
@Slf4j
public class DateUtils {// 常用日期格式public static final String DATE_FORMAT = "yyyy-MM-dd";public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";public static final String DATE_MINUTE_FORMAT = "yyyy-MM-dd HH:mm";public static final String MINUTE_FORMAT = "HH:mm";public DateUtils() {}/*** 获取指定日期当天的开始时间** @param calendar 日历对象* @return 当天的开始时间*/public static Date getStartDate(Calendar calendar) {calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}/*** 获取指定日期当天的结束时间** @param calendar 日历对象* @return 当天的结束时间*/public static Date getEndDate(Calendar calendar) {calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(Calendar.MILLISECOND, 999);return calendar.getTime();}/*** 在指定日期上加上或减去指定天数** @param date 起始日期* @param day  要增加的天数(负数表示减去)* @return 新的日期*/public static Date addDate(Date date, int day) {long millis = date.getTime() + day * 24L * 3600L * 1000L;Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(millis);return calendar.getTime();}/*** 获取指定日期当天的开始时间** @param date 日期对象* @return 当天的开始时间*/public static Date getStartDate(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}/*** 获取指定日期当天的结束时间** @param date 日期对象* @return 当天的结束时间*/public static Date getEndDate(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(Calendar.MILLISECOND, 999);return calendar.getTime();}/*** 计算两个日期之间的周数差** @param startDate 开始日期* @param endDate   结束日期* @return 周数差*/public static int weeksOfTwoDates(Date startDate, Date endDate) {Calendar calendar = Calendar.getInstance();calendar.setTime(endDate);int i = 0;while (!endDate.before(startDate)) {i++;calendar.setFirstDayOfWeek(Calendar.MONDAY);calendar.add(Calendar.WEEK_OF_YEAR, -1);calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());calendar.add(Calendar.DAY_OF_MONTH, 6);endDate = calendar.getTime();}return i;}/*** 获取当前周的周一日期** @return 当前周的周一日期*/public static Date getCurrentMonday() {int mondayPlus = getMondayPlus();GregorianCalendar currentDate = new GregorianCalendar();currentDate.add(Calendar.DAY_OF_MONTH, mondayPlus);return currentDate.getTime();}/*** 获取上周日的日期** @return 上周日的日期*/public static Date getPreviousSunday() {int mondayPlus = getMondayPlus();GregorianCalendar currentDate = new GregorianCalendar();currentDate.add(Calendar.DAY_OF_MONTH, mondayPlus + 6);return currentDate.getTime();}/*** 获取当前日期到最近的周一的天数差** @return 天数差*/public static int getMondayPlus() {Calendar cd = Calendar.getInstance();int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);return dayOfWeek == 1 ? -6 : 2 - dayOfWeek;}/*** 获取当前月的第一天** @return 当前月的第一天*/public static Calendar getMinMonthDate() {Calendar calendar = Calendar.getInstance();calendar.set(5, calendar.getActualMinimum(5));return calendar;}/*** 获取当前月的最后一天** @return 当前月的最后一天*/public static Calendar getMaxMonthDate() {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));return calendar;}/*** 获取上周一的日期** @return 上周一的日期*/public static Calendar getLastMonday() {Calendar calendar = Calendar.getInstance();int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;int offset = 1 - dayOfWeek;calendar.add(Calendar.DAY_OF_MONTH, offset - 7);return calendar;}/*** 获取上周日的日期** @return 上周日的日期*/public static Calendar getLastSunday() {Calendar calendar = Calendar.getInstance();int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;int offset = Calendar.DAY_OF_WEEK - dayOfWeek;calendar.add(Calendar.DAY_OF_MONTH, offset - 7);return calendar;}/*** 获取上个月的第一天** @return 上个月的第一天*/public static Calendar getLastMonthFirstDay() {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.MONTH, -1);calendar.set(Calendar.DAY_OF_MONTH, 1);return calendar;}/*** 获取上个月的最后一天** @return 上个月的最后一天*/public static Calendar getLastMonthEndDay() {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.DAY_OF_MONTH, 0);return calendar;}/*** 将日期对象格式化为字符串** @param date 日期对象* @return 格式化后的字符串*/public static String getDateStr(Date date) {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);return date != null ? sdf.format(date) : "";}/*** 获取指定日期之前的若干天** @param date 日期对象* @param num  天数* @return 指定日期之前的若干天*/public static Date getPreDateStr(Date date, int num) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.DAY_OF_MONTH, -num);Date time = calendar.getTime();return time;}/*** 获取当前周的周一日期** @return 当前周的周一日期*/public static Date getMondayStrOfWeek() {Calendar calendar = Calendar.getInstance();int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);if (dayWeek == 1) {calendar.add(Calendar.DAY_OF_MONTH, -6);} else {calendar.add(Calendar.DAY_OF_MONTH, -(dayWeek - 2));}Date time = calendar.getTime();return time;}/*** 判断指定日期是否为当月的最后一天** @param date 日期对象* @return true 表示是当月的最后一天,否则不是*/public static boolean isLastDayOfMonth(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);int now = calendar.get(Calendar.DAY_OF_MONTH);return now == lastDay;}/*** 计算两个日期之间的天数** @param startDateStr 开始日期字符串* @param endDateStr   结束日期字符串* @return 两个日期之间的天数* @throws Exception 日期解析异常*/public static int daysOfTwo(String startDateStr, String endDateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);Date startDate = sdf.parse(startDateStr);Date endDate = sdf.parse(endDateStr);return (int) ((endDate.getTime() - startDate.getTime()) / 1000L / 60L / 60L / 24L);}/*** 获取最近12天的日期字符串列表** @return 最近12天的日期字符串列表*/public static List<String> getContinue12Days() {List<String> list = new ArrayList<>();Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, -11);SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);for (int i = 0; i <= 11; ++i) {Date time = calendar.getTime();list.add(sdf.format(time));calendar.add(Calendar.DAY_OF_MONTH, 1);}return list;}/*** 获取指定日期的年份周次字符串** @param dateStr 日期字符串* @return 年份周次字符串* @throws Exception 日期解析异常*/public static String getWeeksOfYear(String dateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);Date date = sdf.parse(dateStr);Calendar calendar = Calendar.getInstance();calendar.setTime(date);int i = calendar.get(Calendar.WEEK_OF_YEAR);if (i >= 10) {return dateStr.substring(2, 4) + "-" + i;} else {return dateStr.substring(2, 4) + "-0" + i;}}/*** 将日期字符串解析为日期对象** @param dateStr 日期字符串* @return 日期对象* @throws Exception 日期解析异常*/public static Date getDateByStr(String dateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);return sdf.parse(dateStr);}/*** 计算两个日期之间的天数** @param startDate 开始日期* @param endDate   结束日期* @return 两个日期之间的天数*/public static int daysOfTwoDates(Date startDate, Date endDate) {return (int) ((endDate.getTime() - startDate.getTime()) / 1000L / 60L / 60L / 24L);}/*** 获取指定日期的月份第一天** @param date 日期对象* @return 月份第一天*/public static Date getFirstDayOfMonth(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.DATE, 1);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);return calendar.getTime();}/*** 获取指定年份和月份的最后一天** @param year  年份* @param month 月份* @return 月份最后一天*/public static final Date getLastDayOfMonth(int year, int month) {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR, year);calendar.set(Calendar.MONTH, month - 1);int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);calendar.set(Calendar.DAY_OF_MONTH, lastDay);return calendar.getTime();}/*** 判断指定日期是否是今天** @param date 日期对象* @return true 表示是今天,否则不是*/public static boolean isNow(Date date) {Date now = new Date();SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);String nowDay = sf.format(now);String day = sf.format(date);return day.equals(nowDay);}/*** 将日期对象格式化为指定格式的字符串** @param date   日期对象* @param format 格式字符串* @return 格式化后的日期字符串*/public static String format(Date date, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(date);}/*** 将字符串解析为指定格式的日期对象** @param str    日期字符串* @param format 格式字符串* @return 日期对象* @throws Exception 日期解析异常*/public static Date parse(String str, String format) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.parse(str);}/*** 判断当前时间是否在指定时间范围内** @param nowTime   当前时间* @param startTime 开始时间* @param endTime   结束时间* @return true 表示在范围内,否则不在范围内*/public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {return true;}Calendar date = Calendar.getInstance();date.setTime(nowTime);Calendar begin = Calendar.getInstance();begin.setTime(startTime);Calendar end = Calendar.getInstance();end.setTime(endTime);return date.after(begin) && date.before(end);}/*** 将时间戳格式化为指定格式的日期字符串** @param dateTime 时间戳* @param format   格式字符串* @return 格式化后的日期字符串*/public static String formatLongToDateStr(Long dateTime, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(new Date(dateTime));}
}
2.EncodeUtils.java
package com.sunxiansheng.tool;import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;/*** 编解码工具类,提供BASE64和URL的编解码功能*/
public class EncodeUtils {// 默认的URL编码字符集private static final String DEFAULT_URL_ENCODING = "UTF-8";// BASE64编码器实例private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();// BASE64解码器实例private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();/*** 对文本进行BASE64编码** @param text 需要编码的文本* @return 编码后的字符串* @throws UnsupportedEncodingException 如果字符编码不被支持*/public static String encode(String text) throws UnsupportedEncodingException {// 将文本按指定字符集转换为字节数组,再进行BASE64编码return BASE64_ENCODER.encodeToString(text.getBytes(DEFAULT_URL_ENCODING));}/*** 对BASE64编码的文本进行解码** @param encodedText 需要解码的BASE64编码文本* @return 解码后的字符串* @throws UnsupportedEncodingException 如果字符编码不被支持*/public static String decode(String encodedText) throws UnsupportedEncodingException {// 对BASE64编码的文本进行解码,再按指定字符集转换为字符串return new String(BASE64_DECODER.decode(encodedText), DEFAULT_URL_ENCODING);}/*** 对URL的部分文本进行编码** @param part 需要编码的URL部分文本* @return 编码后的字符串* @throws UnsupportedEncodingException 如果字符编码不被支持*/public static String urlEncode(String part) throws UnsupportedEncodingException {// 使用URLEncoder对文本进行URL编码return URLEncoder.encode(part, DEFAULT_URL_ENCODING);}/*** 对URL的部分文本进行解码** @param part 需要解码的URL部分文本* @return 解码后的字符串* @throws UnsupportedEncodingException 如果字符编码不被支持*/public static String urlDecode(String part) throws UnsupportedEncodingException {// 使用URLDecoder对URL编码的文本进行解码return URLDecoder.decode(part, DEFAULT_URL_ENCODING);}}
3.IpUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;/*** IP工具类*/
@Slf4j
public class IpUtils {private static final String DEFAULT_IP = "127.0.0.1";private static final String UN_KNOWN = "unknown";private static final int IP_MAX_LENGTH = 15;private static final String SPLIT = ",";/*** 获取本地IP地址** @return 本地IP地址字符串*/private static String getLocalIp() {try {InetAddress localHost = InetAddress.getLocalHost();String localIp = localHost.getHostAddress();log.info("IpUtils.getLocalIp:{}", localIp);return localIp;} catch (Exception e) {log.error("IpUtils.getLocalIp.error:{}", e.getMessage(), e);return DEFAULT_IP;}}/*** 从HttpServletRequest中获取客户端IP地址** @param request HttpServletRequest对象* @return 客户端IP地址字符串*/public static String getIp(HttpServletRequest request) {String ip = null;try {ip = request.getHeader("x-forwarded-for");if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (StringUtils.isEmpty(ip) || ip.length() == 0 || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}} catch (Exception e) {log.error("IpUtils.getIp.error:{}", e.getMessage(), e);}if (!StringUtils.isEmpty(ip) && ip.length() > IP_MAX_LENGTH) {if (ip.indexOf(SPLIT) > 0) {ip = ip.substring(0, ip.indexOf(SPLIT));}}return ip;}
}
4.LetterUtils.java
package com.sunxiansheng.tool;import org.apache.commons.lang3.StringUtils;import java.util.Arrays;
import java.util.List;/*** 字母转换工具类*/
public class LetterUtils {/*** 将字母转换为对应的数字。** @param letter 要转换的字母字符串* @return 对应的数字值*/public static long letterToNumber(String letter) {int length = letter.length();long number = 0;for (int i = 0; i < length; i++) {char ch = letter.charAt(length - i - 1);int num = ch - 'A' + 1;number += num;}return number;}/*** 将字符串数组按照指定的分隔符拼接成一个字符串。** @param splitChar 分隔字符* @param args 字符串数组* @return 拼接后的字符串*/public static String assembleHandler(char splitChar, String... args) {List<String> strList = Arrays.asList(args);return StringUtils.join(strList, splitChar);}}
5.MaskUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** 掩码工具类,用于隐藏敏感信息如手机号码、邮箱地址、昵称等*/
@Slf4j
public class MaskUtils {/*** 隐藏手机号码中间的数字,仅保留前3位和后3位** @param mobile 手机号码* @return 掩码后的手机号码*/public static String maskMobile(String mobile) {if (StringUtils.isBlank(mobile)) {return null;}int length = mobile.length();char[] mobileChars = mobile.toCharArray();char[] resultChars = new char[mobile.length()];for (int i = 0; i < length; i++) {if (i >= 3 && i < length - 3) {resultChars[i] = '*';} else {resultChars[i] = mobileChars[i];}}return new String(resultChars);}/*** 隐藏邮箱地址中间的字符,仅保留@前后的字符** @param email 邮箱地址* @return 掩码后的邮箱地址*/public static String maskEmail(String email) {if (StringUtils.isBlank(email)) {return null;}int length = email.length();char[] emailChars = email.toCharArray();char[] resultChars = new char[email.length()];int atIndex = email.indexOf('@');for (int i = 0; i < length; i++) {if (i > 0 && i < atIndex - 1) {resultChars[i] = '*';} else {resultChars[i] = emailChars[i];}}return new String(resultChars);}/*** 过滤xml标签,提取标签中的内容** @param html 包含xml标签的字符串* @return 提取出的标签内容*/public static String getContext(String html) {String result = html;if (StringUtils.isBlank(html)) {return null;}Pattern p = Pattern.compile(">([^</]+)</");Matcher m = p.matcher(html);if (m.find()) {result = m.group(1);}return result;}/*** 隐藏昵称中间的字符,仅保留首尾字符** @param nickName 昵称* @return 掩码后的昵称*/public static String maskNickName(String nickName) {if (StringUtils.isBlank(nickName)) {return "";}int length = nickName.length();char[] nickNameChars = nickName.toCharArray();char[] resultChars = new char[nickName.length()];for (int i = 0; i < length; i++) {if (i > 0 && i < length - 1) {resultChars[i] = '*';} else if (i == 1 && length == 2) {resultChars[i] = '*';} else {resultChars[i] = nickNameChars[i];}}return new String(resultChars);}
}
6.Md5Utils.java
package com.sunxiansheng.tool;import java.security.MessageDigest;/*** MD5 加密工具类*/
public class Md5Utils {/*** 对输入的文本进行MD5加密** @param text 要加密的文本* @return 加密后的十六进制字符串*/public static String encode(String text) {try {// 获取MD5消息摘要实例MessageDigest md = MessageDigest.getInstance("MD5");// 更新摘要,使用指定的字节数组md.update(text.getBytes());// 计算摘要并返回字节数组byte[] digest = md.digest();// 将字节数组转换为十六进制字符串StringBuilder result = new StringBuilder();for (byte b : digest) {result.append(String.format("%02x", b & 0xff));}return result.toString();} catch (Exception e) {// 捕获异常并打印堆栈信息e.printStackTrace();return null;}}}
7.PinYin4jUtils.java
package com.sunxiansheng.tool;import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;/*** 拼音工具类,用于将汉字转换为拼音*/
public class PinYin4jUtils {/*** 将汉字转换为全拼** @param src 要转换的汉字字符串* @return 转换后的拼音字符串*/public static String getPinYin(String src) {char[] hz = src.toCharArray();String[] py;HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);format.setVCharType(HanyuPinyinVCharType.WITH_V);StringBuilder pys = new StringBuilder();int len = hz.length;try {for (int i = 0; i < len; i++) {// 先判断是否为汉字字符if (Character.toString(hz[i]).matches("[\\u4E00-\\u9FA5]+")) {// 将汉字的几种全拼都存到py数组中py = PinyinHelper.toHanyuPinyinStringArray(hz[i], format);// 取出该汉字全拼的第一种读音,并存放到字符串pys后pys.append(py[0]);} else {// 如果不是汉字字符,间接取出字符并连接到pys后pys.append(hz[i]);}}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}return pys.toString();}/*** 提取每个汉字的首字母** @param str 要转换的汉字字符串* @return 转换后的拼音首字母字符串*/public static String getPinYinHeadChar(String str) {StringBuilder convert = new StringBuilder();for (int i = 0; i < str.length(); i++) {char word = str.charAt(i);// 提取汉字的首字母String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);if (pinyinArray != null) {convert.append(pinyinArray[0].charAt(0));} else {convert.append(word);}}return convert.toString().toUpperCase();}/*** 提取首个汉字的首字母** @param str 要转换的汉字字符串* @return 转换后的首字母*/public static String getPinYinFirstHeadChar(String str) {String convert = "";String reg = "[^\u4e00-\u9fa5]";str = str.replaceAll(reg, "").replace(" ", "");if (str.length() > 0) {char word = str.charAt(0);// 提取汉字的首字母String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);if (pinyinArray != null) {convert += pinyinArray[0].charAt(0);} else {convert += word;}return convert.toUpperCase();} else {return "";}}/*** 将字符串转换为ASCII码** @param str 要转换的字符串* @return 转换后的ASCII码字符串*/public static String getCnASCII(String str) {StringBuilder buf = new StringBuilder();// 将字符串转换成字节序列byte[] bGBK = str.getBytes();for (byte b : bGBK) {// 将每个字符转换成ASCII码buf.append(Integer.toHexString(b & 0xff));}return buf.toString();}
}
8.PropertiesUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;/*** 属性文件读取工具类* 用于读取属性文件(properties)的工具类*/
@Slf4j
public class PropertiesUtils {/*** 属性文件与属性集合的关系* Map 用于存储每个属性文件的属性键值对*/private Map<String, Properties> propertiesMap = new HashMap<>();/*** 属性文件与修改时间的关系* Map 用于存储每个属性文件的最后修改时间*/private Map<String, Long> modifyTimeMap = new HashMap<>();/*** 指定的属性文件的目录路径*/private String configPath = "";/*** 单例模式构造方法私有化*/private PropertiesUtils() {}/*** 静态内部类单例模式*/private static class SingleHolder {private static final PropertiesUtils INSTANCE = new PropertiesUtils();}/*** 获取 PropertiesUtils 实例** @return PropertiesUtils 实例*/public static PropertiesUtils getInstance() {return SingleHolder.INSTANCE;}/*** 配置属性文件目录路径** @param path 属性文件目录路径*/public void configure(String path) {this.configPath = path;}/*** 获取指定属性的值** @param propertyFileName 属性文件名* @param key 属性键* @return 属性值*/public String getPropertyValue(String propertyFileName, String key) {String fileName = convertPropertiesFileName(propertyFileName);try {if (propertiesMap.get(fileName) == null) {loadProperties(fileName);} else {checkPropertiesFileModified(fileName);}return propertiesMap.get(fileName).getProperty(key);} catch (Exception e) {log.error("PropertiesUtils.getPropertyValue.error:{}", e.getMessage(), e);}return "";}/*** 对传入的属性文件名称进行处理,如果包含.properties后缀则去掉** @param propertyFileName 属性文件名* @return 处理后的属性文件名*/private String convertPropertiesFileName(String propertyFileName) {String fileName = propertyFileName;if (fileName.endsWith(".properties")) {int index = fileName.lastIndexOf(".");fileName = fileName.substring(0, index);}return fileName;}/*** 加载指定名称的属性文件** @param shortPropertyFileName 属性文件短名(不包含路径和扩展名)* @throws URISyntaxException URI语法异常*/private void loadProperties(String shortPropertyFileName) throws URISyntaxException {File file = getPropertiesFile(shortPropertyFileName);Long newTime = file.lastModified();if (propertiesMap.get(shortPropertyFileName) != null) {propertiesMap.remove(shortPropertyFileName);}Properties props = new Properties();try {props.load(new FileInputStream(file));} catch (Exception e) {log.error("PropertiesUtils.loadProperties.error:{}", e.getMessage(), e);}propertiesMap.put(shortPropertyFileName, props);modifyTimeMap.put(shortPropertyFileName, newTime);}/*** 检查属性文件有无更新,若更新则重新加载** @param shortPropertyFileName 属性文件短名(不包含路径和扩展名)* @throws URISyntaxException URI语法异常*/private void checkPropertiesFileModified(String shortPropertyFileName) throws URISyntaxException {File file = getPropertiesFile(shortPropertyFileName);Long newTime = file.lastModified();Long lastModifiedTime = modifyTimeMap.get(shortPropertyFileName);if (newTime == 0) {if (lastModifiedTime == null) {log.error(shortPropertyFileName + ".properties file does not exist!");}} else if (newTime > lastModifiedTime) {loadProperties(shortPropertyFileName);}}/*** 获取属性文件的绝对路径** @param shortPropertyFileName 属性文件短名(不包含路径和扩展名)* @return 属性文件对象* @throws URISyntaxException URI语法异常*/private File getPropertiesFile(String shortPropertyFileName) throws URISyntaxException {File propertiesFile;if (this.configPath != null && !this.configPath.trim().isEmpty()) {return new File(this.configPath + File.separator + shortPropertyFileName + ".properties");}String dir = System.getProperty("user.dir") + File.separator + shortPropertyFileName + ".properties";propertiesFile = new File(dir);if (!propertiesFile.exists()) {URL url = PropertiesUtils.class.getResource("/" + shortPropertyFileName + ".properties");if (url == null) {propertiesFile = null;} else {propertiesFile = new File(url.toURI());}}return propertiesFile;}
}
9.SimpleDateFormatUtils.java
package com.sunxiansheng.tool;import java.text.SimpleDateFormat;/*** SimpleDateFormat 工具类* 用于提供线程安全的 SimpleDateFormat 实例*/
public class SimpleDateFormatUtils {// 使用 ThreadLocal 提供线程安全的 SimpleDateFormat 实例private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {/*** 初始化 SimpleDateFormat 实例* @return SimpleDateFormat 实例,格式为 "yyyy-MM-dd HH:mm:ss"*/@Overrideprotected SimpleDateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};/*** 获取时间格式化实例* @return SimpleDateFormat 实例,格式为 "yyyy-MM-dd HH:mm:ss"*/public static SimpleDateFormat getTime() {SimpleDateFormat simpleDateFormat = THREAD_LOCAL.get();// 如果 THREAD_LOCAL 中没有 SimpleDateFormat 实例,则创建新的实例if (simpleDateFormat == null) {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}return simpleDateFormat;}}
10.SpringContextUtils.java
package com.sunxiansheng.tool;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;/*** Spring上下文工具类,用于获取Spring容器中的Bean及HTTP请求、响应、会话对象。* 实现ApplicationContextAware接口,以便自动注入ApplicationContext。* 通过Spring的@Component注解注册为Spring Bean。*/
@Component
public class SpringContextUtils implements ApplicationContextAware {// Spring应用上下文环境private static ApplicationContext applicationContext;/*** 实现ApplicationContextAware接口的setApplicationContext方法,用于注入ApplicationContext。* @param applicationContext Spring应用上下文* @throws BeansException Beans异常*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}/*** 获取Spring应用上下文。* @return Spring应用上下文*/public static ApplicationContext getApplicationContext() {return applicationContext;}/*** 根据名称获取Bean。* @param name Bean名称* @return Bean实例* @throws BeansException Beans异常*/public static Object getBean(String name) throws BeansException {return applicationContext.getBean(name);}/*** 根据名称和类型获取Bean。* @param name Bean名称* @param requiredType Bean类型* @return Bean实例* @throws BeansException Beans异常*/public static Object getBean(String name, Class requiredType) throws BeansException {return applicationContext.getBean(name, requiredType);}/*** 根据类型获取Bean。* @param requiredType Bean类型* @return Bean实例* @throws BeansException Beans异常*/public static Object getBean(Class requiredType) throws BeansException {return applicationContext.getBean(requiredType);}/*** 根据类型获取Bean,返回指定类型的实例。* @param <T> Bean类型* @param clazz Bean类* @return Bean实例*/public static <T> T getBeanByType(Class<T> clazz) {return applicationContext.getBean(clazz);}/*** 判断是否包含指定名称的Bean。* @param name Bean名称* @return 是否包含指定名称的Bean*/public static boolean containsBean(String name) {return applicationContext.containsBean(name);}/*** 判断指定名称的Bean是否为单例。* @param name Bean名称* @return 是否为单例* @throws NoSuchBeanDefinitionException 没有找到指定名称的Bean异常*/public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {return applicationContext.isSingleton(name);}/*** 获取指定名称的Bean的类型。* @param name Bean名称* @return Bean类型* @throws NoSuchBeanDefinitionException 没有找到指定名称的Bean异常*/public static Class getType(String name) throws NoSuchBeanDefinitionException {return applicationContext.getType(name);}/*** 获取指定类型的所有Bean。* @param <T> Bean类型* @param clazz Bean类* @return Bean实例Map* @throws NoSuchBeanDefinitionException 没有找到指定名称的Bean异常*/public static <T> Map<String, T> getBeanOfType(Class<T> clazz) throws NoSuchBeanDefinitionException {return applicationContext.getBeansOfType(clazz);}/*** 获取指定名称的Bean的别名。* @param name Bean名称* @return Bean别名数组* @throws NoSuchBeanDefinitionException 没有找到指定名称的Bean异常*/public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {return applicationContext.getAliases(name);}/*** 获取当前HTTP请求对象。* @return 当前HTTP请求对象*/public static HttpServletRequest getHttpServletRequest() {return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();}/*** 获取当前HTTP响应对象。* @return 当前HTTP响应对象*/public static HttpServletResponse getHttpServletResponse() {return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();}/*** 获取当前HTTP会话对象。* @return 当前HTTP会话对象*/public static HttpSession getHttpSession() {HttpServletRequest request = getHttpServletRequest();return request.getSession();}
}
11.ThreadPoolUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;/*** 线程池工具类*/
@Slf4j
public class ThreadPoolUtils {/*** 私有构造方法,防止实例化该工具类。*/private ThreadPoolUtils() {}/*** 优雅地关闭线程池** @param pool 需要关闭的线程池* @param shutdownTimeout 调用shutdown后等待线程池终止的时间* @param shutdownNowTimeout 调用shutdownNow后等待线程池终止的时间* @param timeUnit 时间单位*/public static void shutdownPool(ExecutorService pool, int shutdownTimeout, int shutdownNowTimeout, TimeUnit timeUnit) {// 调用shutdown以开始优雅地关闭线程池pool.shutdown();try {// 等待所有任务完成或超时if (!pool.awaitTermination(shutdownTimeout, timeUnit)) {// 调用shutdownNow强制关闭线程池pool.shutdownNow();// 再次等待所有任务完成或超时if (!pool.awaitTermination(shutdownNowTimeout, timeUnit)) {log.error("ThreadPoolUtils.shutdownPool.error");}}} catch (InterruptedException ie) {// 捕获中断异常并记录错误信息log.error("ThreadPoolUtils.shutdownPool.interrupted.error:{}", ie.getMessage(), ie);// 再次调用shutdownNow强制关闭线程池pool.shutdownNow();// 设置当前线程中断状态Thread.currentThread().interrupt();}}
}
12.UuidUtils.java
package com.sunxiansheng.tool;import java.util.UUID;/*** UUID工具类*/
public class UuidUtils {// 字符集,用于生成短UUIDpublic static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u","v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};/*** 生成标准的UUID字符串** @return UUID字符串*/public static String getUuid() {return UUID.randomUUID().toString();}/*** 生成去除“-”的32位UUID字符串** @return 去除“-”的UUID字符串*/public static String getUuid32() {return UUID.randomUUID().toString().replace("-", "");}/*** 生成8位短UUID字符串** @return 8位短UUID字符串*/public static String getUuid8() {StringBuilder shortBuffer = new StringBuilder();// 生成UUID,并去除“-”String uuid = UUID.randomUUID().toString().replace("-", "");// 将UUID分为8组,每组4位for (int i = 0; i < 8; i++) {// 取出每组的4位字符串String str = uuid.substring(i * 4, i * 4 + 4);// 将4位字符串转换为16进制表示的int类型int x = Integer.parseInt(str, 16);// 取模62,将结果作为索引取出字符集中的字符shortBuffer.append(chars[x % 62]);}return shortBuffer.toString();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/64395.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

构建一个rust生产应用读书笔记四(实战3)

从这一节开始&#xff0c;我们将继续完善邮件订阅生产级应用&#xff0c;根据作者的选型sqlx作为数据库操作的类库&#xff0c;它有如下优点&#xff1a; 它旨在提供高效、安全且易于使用的数据库交互体验。sqlx 支持多种数据库&#xff0c;包括 PostgreSQL、MySQL 和 SQLite&…

视频直播点播平台EasyDSS推拉流技术结合无人机推流在道路交通巡检场景中的应用

随着城市化进程的加速&#xff0c;交通网络日益复杂&#xff0c;交通巡检工作面临着前所未有的挑战。传统的巡检方式往往依赖于人工巡查或地面监控设备&#xff0c;但这些方法存在巡检范围有限、效率低下等缺点。 无人机凭借其高空视野、灵活机动、实时监控等优势&#xff0c;…

VBA技术资料MF238:ADO提取多文件区域指定数据到工作表

我给VBA的定义&#xff1a;VBA是个人小型自动化处理的有效工具。利用好了&#xff0c;可以大大提高自己的工作效率&#xff0c;而且可以提高数据的准确度。“VBA语言専攻”提供的教程一共九套&#xff0c;分为初级、中级、高级三大部分&#xff0c;教程是对VBA的系统讲解&#…

Mapper代理开发

引入 Mybatis入门方式中&#xff0c;以下代码仍存在硬编码问题 Mapper 代理开发&#xff1a; 目的&#xff1a; 解决原生方式中的硬编码 简化后期执行sql ------下图中&#xff0c;第一段代码是原生硬编码代码块&#xff0c;第二个是引入了Mapper代理开发的代码块。 Mapper代…

ubuntu22.04编译安装Opencv4.8.0+Opencv-contrib4.8.0教程

本章教程,主要记录在Ubuntu22.04版本系统上编译安装安装Opencv4.8.0+Opencv-contrib4.8.0的具体过程。 一、下载opencv和opencv-contrib包 wget https://github.com/opencv/opencv/archive/refs/tags/4.8.0.zip wget https://github.com/opencv/opencv_contrib/archive/refs/…

使用C语言连接MySQL

库的准备 要使用C语言连接mysql&#xff0c;需要使用mysql官网提供的connect库&#xff0c;可以去官网下载&#xff0c;由于我们要下载到 Linux 操作系统中&#xff0c;也可以使用如下指令进行安装库 sudo apt-get install libmysqlclient-dev MySQL连接C/C的库通常会安装在/us…

【Android学习】RxJava

文章目录 资料连接1. Merge & Zip操作符: 合并数据源2. Map & FlapMap & ConcatMap & Buffer: 变换操作符3. retry & retryUntil & retryWhen : 错误处理操作符4. Transformer & Compose 转换操作符5. 网络请求嵌套回调 FlatMap6. 网络请求出错重连…

Mac配置 Node镜像源的时候报错解决办法

在Mac电脑中配置国内镜像源的时候报错,提示权限问题,无法写入配置文件。本文提供解决方法,青测有效。 一、原因分析 遇到的错误是由于 .npm 目录下的文件被 root 用户所拥有,导致当前用户无法写入相关配置文件。 二、解决办法 在终端输入以下命令,输入管理员密码即可。 su…

PyTorch基础入门

目录 前言一、[张量的广播&基本运算](https://www.bilibili.com/video/BV1Gg411u7Lr/?spm_id_from333.999.0.0)1. 张量的广播特性2. 逐点&规约&比较运算 二、张量的线性代数运算1. BLAS & LAPACK2. 矩阵形变及特殊矩阵构造3. 矩阵基本运算4. 矩阵的线性代数运…

【VSCode】常用插件汇总

1 Path Autocomplete&#xff08;路径提示的插件&#xff09; 步骤一&#xff1a;在vscode的扩展搜索中直接搜索Path Autocomplete&#xff0c;直接安装 步骤二&#xff1a;配置 配置 VS Code settings.json "path-autocomplete.pathMappings": {"": &q…

IOS通过WDA自动化中遇到的问题

IOS自动化遇到的问题 搭建WDA环境中遇到的问题1、XCode unsupport iphone xxx.2、创建Bundle Identifier出现问题&#xff1a;Communication with Apple failed3、创建Bundle Identifier出现问题&#xff1a;Automatic signing failed \Signing certificate is invalid4、创建B…

(六)- DRM驱动开发(qcom)

一&#xff0c;Linux Android Display 1&#xff0c;Linux Android Display Software Subsystem 密 2&#xff0c;Linux Android Display Architecture 密 二&#xff0c;DRM/KMS Adreno DPU 1&#xff0c;硬件框图 密 1.1 Qualcomm Adreno DPU 8-Series Overview 密 …

游戏AI实现-寻路算法(GBFS)

贪婪最佳优先算法是宽度优先遍历和贪婪算法结合的产物&#xff0c;使用启发式函数选择当前最低代价的节点&#xff0c;改善了宽度优先遍历需要遍历地图的大量节点来找寻结果的缺点。 算法过程&#xff1a; 1.首先设置开始节点的启发函数值&#xff08;h&#xff09;为0&#…

[Unity]Unity跨平台开发之Android简介

Android要求和兼容 图形接口支持 注意&#xff1a; 新的 Unity 项目默认不支持 OpenGL ES 2.0。 由于硬件和图形 API 的限制&#xff0c;并非所有渲染管道都与 Android 兼容。 图片压缩 Android标准压缩格式是ETC和ASTC。Unity默认压缩格式是ASTC。如果Android设备不支持您选…

监控易在汽车制造行业信息化运维中的应用案例

引言 随着汽车制造行业的数字化转型不断深入&#xff0c;信息化类IT软硬件设备的运行状态监控、故障告警、报表报告以及网络运行状态监控等成为了企业运维管理的关键环节。监控易作为一款全面、高效的信息化运维管理工具&#xff0c;在汽车制造行业中发挥着重要作用。本文将结合…

Trimble天宝三维激光扫描仪在建筑工程竣工测量中的应用【沪敖3D】

竣工测量是建筑项目竣工阶段的一个至关重要的环节&#xff0c;它为建筑工程的质量验收和成果核查提供了核心的参考依据。传统的竣工测量方法&#xff0c;如全站仪测量&#xff0c;主要依赖于现场人工操作&#xff0c;存在一些明显的局限性&#xff0c;例如作业时间长、工作量大…

健康养生:拥抱生活的艺术

健康养生&#xff1a;拥抱生活的艺术 在快节奏的现代生活中&#xff0c;健康已成为我们最宝贵的财富。健康养生&#xff0c;不仅仅是一种生活方式的选择&#xff0c;更是一种对待生活的态度&#xff0c;它关乎于如何在日常中寻找到平衡&#xff0c;让身心得以滋养&#xff0c;…

【C语言程序设计——入门】基本数据类型与表达式(头歌实践教学平台习题)【合集】

目录&#x1f60b; <第1关&#xff1a;print 函数操作> 任务描述 相关知识 编程要求 测试说明 我的通关代码: 测试结果&#xff1a; <第2关&#xff1a;转义字符使用> 任务描述 相关知识 编程要求 测试说明 我的通关代码: 测试结果&#xff1a; <…

C++算法第九天

本篇文章我们继续学习c算法 目录 第一题 题目链接 题目展示 代码原理 暴力解法 二分解法 代码编写 第二题 题目链接 题目展示 代码原理 代码编写 重点回顾 朴素二分 非朴素二分 重点一 重点二 重点三 第一题 题目链接 153. 寻找旋转排序数组中的最小值 - 力…

Mysql学习笔记之SQL-2

上篇文章介绍了SQL语句的第一部分数据定义语言&#xff08;DDL)&#xff0c;这篇文章我们介绍SQL语句的第二部分&#xff0c;数据库操作语言&#xff08;DML&#xff09; 1.简介 DML全称&#xff08;Data Manipulation Language&#xff09;&#xff0c;用来对数据表中的数据…