文章目录

  • 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"
             */
            @Override
            protected 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异常
         */
        @Override
        public 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 {
    
        // 字符集,用于生成短UUID
        public 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();
        }
    }
    

    作者:S-X-S

    物联沃分享整理
    物联沃-IOTWORD物联网 » 编写工具模块

    发表回复