工作中Hutool包的常用方法总结

平常工作经常用到hutool工具包,久而久之我就把这些常用的方法慢慢记录下来了,大家可以简单看一下

异常信息String化打印

单独的工具方法

public class ExceptionUtil {
    // 以上代码通过将异常信息打印到 StringWriter 对象中,然后获取 StringWriter 的字符串表示,从而获取到异常信息的字符串。
    public static String toString(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
}

Exception具体报错内容转string

    public static void main(String[] args) {
        try {
            int i =  1/0;
        } catch (Exception e) {
            System.out.println(ExceptionUtil.stacktraceToString(e));
        }

    }

打印出来的内容:

java.lang.ArithmeticException: / by zero
	at com.bofei.activity.task.LoanActiveTask.main(LoanActiveTask.java:147)

元素操作

对象List切割

按照批次分割数组,如1000个元素分四批

List<List<LoanInfoBulkChargeVO>> batchTotalList = ListUtil.splitAvg(collect, bulkDeductionBatchTotal);

按照数量分割数组,如2000个元素按200为一个组进行划分

// 按照200为一组进行划分
List<List<Integer>> resultList = ListUtil.split(originalList, 200);

对两个list队列内元素做交并集操作

public static void main(String[] args) {
    List list1 = new ArrayList<String>();
    list1.add("a");
    list1.add("b");
    list1.add("c");

    List list2 = new ArrayList<String>();
    list2.add("b");
    list2.add("c");
    list2.add("d");

    // 求交集
    List<String> intersection = (List<String>) CollUtil.intersection(list1, list2);
    System.out.println("交集:" + intersection);

    // 求差集(list1中有而list2中没有的元素)
    List<String> difference = (List<String>) CollUtil.subtract(list1, list2);
    System.out.println("差集:" + difference);

    // 求并集
    List<String> union = (List<String>) CollUtil.union(list1, list2);
    System.out.println("并集:" + union);

    // 判断两个列表是否完全相同
    boolean isEqual = CollUtil.isEqualList(list1, list2);
    System.out.println("是否完全相同:" + isEqual);
    
    // 使用containsAll方法判断list1是否包含list2的所有元素
    boolean isSameCollection = list1.containsAll(list2);
    System.out.println("两个集合是否完全相同:" + isSameCollection);
}
交集:[b, c]
差集:[a]
并集:[a, b, c, d]
是否完全相同:false
两个集合是否完全相同:true

List < entity >对象元素转换List < entityVO >

    public static void main(String[] args) {
        // 原始List
        List<EmergencyContact> personList = new ArrayList<>();
        personList.add(EmergencyContact.builder().phone("123").build());
        personList.add(EmergencyContact.builder().phone("456").build());
        personList.add(EmergencyContact.builder().phone("789").build());

        List<EmergencyContact> personList2 = new ArrayList<>();
        personList2.add(EmergencyContact.builder().phone("123").build());
        personList2.add(EmergencyContact.builder().phone("456").build());
        personList2.add(EmergencyContact.builder().phone("789").build());


        // 将原始List的元素类型转换为PersonVO的List
        List<EmergencyContactVO> personVOList1 = BeanUtil.copyToList(personList, EmergencyContactVO.class);
        List<EmergencyContactVO> personVOList2 = BeanUtil.copyToList(personList2, EmergencyContactVO.class);

        // 输出转换后的PersonVO的List
        for (EmergencyContactVO personVO : personVOList1) {
            System.out.println(personVO.getPhone() + " - " + personVOList1.containsAll(personVOList2));
        }
    }
123 - true
456 - true
789 - true

数值、对象比较

        System.out.println(ObjectUtil.equal(1, "1")); // false
        System.out.println(ObjectUtil.equal(1, 1)); // true
        System.out.println(ObjectUtil.equal("", " "));  // false
        System.out.println(ObjectUtil.equal(null, " ")); // false
        System.out.println(ObjectUtil.equal(null, ""));  // false
        System.out.println(ObjectUtil.equal(Integer.parseInt("1000001"), 1000001));  // true
        System.out.println(ObjectUtil.equal(Integer.parseInt("1000001"), Integer.parseInt("1000001")));  // true
        User user = new User();
        User user1 = new User();
        System.out.println(ObjectUtil.equal(user, user1)); // true
        user.setAge(23);
        System.out.println(ObjectUtil.equal(user, user1)); // false
        user1.setAge(23);
        System.out.println(ObjectUtil.equal(user, user1)); // true

日期相关

日期转换

   		//1.日期转换
        String dateStr = "2020-01-23T12:23:56";
        DateTime dt = DateUtil.parse(dateStr); //2020-01-23 12:23:56
        //Date对象转LocalDateTime
        LocalDateTime of = LocalDateTimeUtil.of(dt); //2020-01-23T12:23:56
        //时间戳转为LocalDateTime
        of = LocalDateTimeUtil.ofUTC(dt.getTime()); //2020-01-23T12:23:56

日期字符串解析

    //解析ISO时间
    LocalDateTime localDateTime = LocalDateTimeUtil.parse("2020-01-23T12:23:56"); //2020-01-23T12:23:56
    //解析自定义格式时间 转成ISO时间
    localDateTime = LocalDateTimeUtil.parse("2020-01-23",DatePattern.NORM_DATE_PATTERN);//2020-01-23T00:00
    //转化为LocalDate
    LocalDate localDate = LocalDateTimeUtil.parseDate("2020-01-23"); //2020-01-23
    //解析日期时间为LocalDate,时间部分舍弃
    localDate = LocalDateTimeUtil.parseDate("2020-01-23T12:23:56", DateTimeFormatter.ISO_DATE_TIME); //2020-01-23

日期格式化(最常用)

    LocalDateTime localDateTime1 = LocalDateTimeUtil.parse("2020-01-23T12:23:56");
    String format = LocalDateTimeUtil.format(localDateTime, DatePattern.NORM_DATETIME_PATTERN); //2020-01-23 12:23:56
    String time = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATETIME_PATTERN); //2022-03-30 16:05:59

日期偏移

    final LocalDateTime localDateTime2 = LocalDateTimeUtil.parse("2020-01-23T12:23:56");
    // 增加一天   增减天数也可以用LocalDateTime中的方法
    LocalDateTime offset = LocalDateTimeUtil.offset(localDateTime2, 1, ChronoUnit.DAYS); // "2020-01-24T12:23:56"
    String offsetString = LocalDateTimeUtil.format(offset,DatePattern.NORM_DATETIME_PATTERN);

计算日期间隔

    LocalDateTime start = LocalDateTimeUtil.parse("2019-02-02T00:00:00");
    LocalDateTime end = LocalDateTimeUtil.parse("2020-02-02T00:00:00");
    Duration between = LocalDateTimeUtil.between(start, end);
    //365
    between.toDays();

一天的开始和结束

    LocalDateTime localDateTime3 = LocalDateTimeUtil.parse("2020-01-23T12:23:56");
    LocalDateTime beginOfDay = LocalDateTimeUtil.beginOfDay(localDateTime); //2020-01-23T00:00
    LocalDateTime endOfDay = LocalDateTimeUtil.endOfDay(localDateTime); //2020-01-23T23:59:59.999999999

JSON操作

JSONUtil

创建json字符串

JSONUtil.toJsonStr可以将任意对象(Bean、Map、集合等)直接转换为JSON字符串。 如果对象是有序的Map等对象,则转换后的JSON字符串也是有序的。

SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
    private static final long serialVersionUID = 1L;
    {
    put("attributes", "a");
    put("b", "b");
    put("c", "c");
}};

JSONUtil.toJsonStr(sortedMap);

结果:

{"attributes":"a","b":"b","c":"c"}

如果我们想获得格式化后的JSON,则:

JSONUtil.toJsonPrettyStr(sortedMap);

结果:

{
    "attributes": "a",
    "b": "b",
    "c": "c"
}

JSON字符串解析(读取特定字段键值)

String html = "{\"name\":\"Something must have been changed since you leave\"}";
JSONObject jsonObject = JSONUtil.parseObj(html);
jsonObject.getStr("name");

JSON转Bean

@Data
public class ADT {
    private List<String> BookingCode;
}

@Data
public class Price {
    private List<List<ADT>> ADT;
}
String json = "{\"ADT\":[[{\"BookingCode\":[\"N\",\"N\"]}]]}";

Price price = JSONUtil.toBean(json, Price.class);

// 
price.getADT().get(0).get(0).getBookingCode().get(0);

JSON转List

 		List<ShopType> typeList = query().orderByAsc("sort").list();

        // 将ShopType转为String
        String jsonStr = JSONUtil.toJsonStr(typeList);

        // 4.保存到redis
        // string类型
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,jsonStr);

		String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if (StrUtil.isNotBlank(shopTypeJson)) {
            // 2.存在直接返回
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypes);
        }

XML字符串转换为JSON

String s = "<sfzh>123</sfzh><sfz>456</sfz><name>aa</name><gender>1</gender>";
JSONObject json = JSONUtil.parseFromXml(s);

json.get("sfzh");
json.get("name");

JSON转换为XML

final JSONObject put = JSONUtil.createObj()
        .set("aaa", "你好")
        .set("键2", "test");

// <aaa>你好</aaa><键2>test</键2>
final String s = JSONUtil.toXmlStr(put);

其它方法

除了上面中常用的一些方法,JSONUtil还提供了一些JSON辅助方法:

  • quote 对所有双引号做转义处理(使用双反斜杠做转义)
  • wrap 包装对象,可以将普通任意对象转为JSON对象
  • formatJsonStr 格式化JSON字符串,此方法并不严格检查JSON的格式正确与否

数字工具-NumberUtil

加减乘除
NumberUtil.add 针对数字类型做加法
NumberUtil.sub 针对数字类型做减法
NumberUtil.mul 针对数字类型做乘法
NumberUtil.div 针对数字类型做除法,并提供重载方法用于规定除不尽的情况下保留小数位数和舍弃方式。

以上四种运算都会将double转为BigDecimal后计算,解决float和double类型无法进行精确计算的问题。这些方法常用于商业计算。

Base64编码

import cn.hutool.core.codec.Base64;

String source = "Base64 Encoding";
String encoded = Base64.encode(source); // 进行Base64编码
String decoded = Base64.decodeStr(encoded); // 进行Base64解码

文件操作

文件读取

import cn.hutool.core.io.FileUtil;

String content = FileUtil.readUtf8String("文件具体路径/文件名"); // 读取文件内容
// String content = FileUtil.readUtf8String("D:\\java_project\\LogServiceImpl.java"); 

上传下载操作

请求并转换为字节数组

template:
	url: https//:xxxx.doc
@Value("${template.url}")
String fileUrl;
byte[] bytes = HttpUtil.downloadBytes(fileUrl);

请求并下载到本地

@Value("${template.url}")
String fileUrl;
byte[] bytes = HttpUtil.downloadFile(fileUrl,"目标文件或目录",30*1000);
 		 @Test
    	public void testDateUtil(){
        //使用下面这三种输出都是一样的结果
        Date originalDate = new Date(); //Wed Mar 16 11:56:29 CST 2022
        Date date = DateUtil.date(); //2022-03-16 11:55:42
        Date date1 = DateUtil.date(Calendar.getInstance()); //2022-03-16 11:55:42
        Date date2 = DateUtil.date(System.currentTimeMillis()); //2022-03-16 11:55:42

        //得到字符串形式
        String stringDate = DateUtil.now();//2022-03-16 11:55:42  string类型
        String stringToday = DateUtil.today(); //2022-03-16 string类型

        //字符串转日期
        Date stringToDate = DateUtil.parse(stringDate); //2022-03-16 11:55:42

        //格式化日期输出
        String stringdate = "2022-03-16 11:55:42";
        Date date3 = DateUtil.parse(stringdate);
        String format = DateUtil.format(date3,"yyyy-MM-dd"); //2022-03-16 格式化还是得用这个,上面的DateUtil.parse有问题
        String format1 = DateUtil.formatDate(date3); //2022-03-16
        String format2 = DateUtil.formatDateTime(date3); //2022-03-16 11:55:42
        String format3 = DateUtil.formatTime(date3); //11:55:42

        //获取Date对象的某个部分
        int year = DateUtil.year(date);  //获得年的部分  输出 2022
        int month = DateUtil.month(date);  //获得月份,从0开始计数     输出 2 也就是3月
        Enum monthEnum = DateUtil.monthEnum(date); //获得月份枚举 输出 MARCH

        //获得每天的开始时间、结束时间,每月的开始和结束时间等等 使用上面date3
        Date beginOfDay = DateUtil.beginOfDay(date3); //2022-03-16 00:00:00 每天的开始时间
        String stringBeginOfDay = DateUtil.format(beginOfDay, DatePattern.NORM_DATETIME_FORMATTER); //转换为string
        Date endOfDay = DateUtil.endOfDay(date3); //2022-03-16 23:59:59 每天的结束时间

        /**
         * 针对当前时间,提供了简化的偏移方法
         * DateUtil.yesterday() //昨天
         * DateUtil.tomorrow() //明天
         * DateUtil.lastWeek() //上周
         * DateUtil.nextWeek() //下周
         * DateUtil.lastMonth() //上个月
         * DateUtil.nextMonth() //下个月
         */
        //日期时间偏移 日期的变更
        Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2); //2022-03-18 16:12:41 增加两天
        DateTime newDate2 = DateUtil.offsetDay(date, 3); //2022-03-19 16:14:07 增加三天
        DateTime newDate3 = DateUtil.offsetHour(date, -3); //2022-03-16 13:14:53 减少三小时

        //日期时间差
        String dateStr1 = "2017-03-01 22:33:23";
        Date dateOne = DateUtil.parse(dateStr1);
        String dateStr2 = "2017-04-01 23:33:23";
        Date dateTwo = DateUtil.parse(dateStr2);
        Long days = DateUtil.between(dateOne,dateTwo,DateUnit.MS); //输出2682000000  
        //格式化时间差 上面是秒下面是毫秒 差一等级才能转换
        String formatBetween = DateUtil.formatBetween(days, BetweenFormatter.Level.MILLISECOND); //31天1小时

        //星座和属相
        String zodiac = DateUtil.getZodiac(Month.JANUARY.getValue(), 19); // "摩羯座"
        String chineseZodiac = DateUtil.getChineseZodiac(2022); //虎
    }
	
		

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
hutool工具常用括类型转换工具类(Convert)、字符串工具类(StrUtil / StringUtils)、日期工具类(DateUtil)、数字工具类(NumberUtil)、数组工具类(ArrayUtil)、随机工具类(RandomUtil)、比较器工具类(ComparatorUtil)、多线程工具类(ThreadUtil)、IO流工具类(FileUtil)、集合工具类(CollUtil / CollectionsUtils)、正则工具类(ReUtil)、网络工具类(NetUtil)、JSON工具类(JSONUtil)、系统信息工具类(SystemUtil)等等。这些工具类提供了一系列常用方法和功能,能够帮助开发者更加方便地进行类型转换、字符串处理、日期操作、数字处理、数组操作、随机数生成、多线程管理、IO流操作、集合操作、正则表达式匹配、网络操作、JSON处理、系统信息获取等等。通过使用hutool工具类,开发者可以提高开发效率,减少代码量,提供更加稳定和高效的程序功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Hutool常用工具类](https://blog.csdn.net/abst122/article/details/124091375)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [hutool 工具类](https://download.csdn.net/download/LiHaoYang11/12153632)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [常用工具类 (三) : Hutool 常用工具类整理 (全)](https://blog.csdn.net/m0_37989980/article/details/126401041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值