yinshuang

  • 个人主页
所有文章 友链 关于我

这似乎是首纯音乐,请尽情的欣赏它吧!

yinshuang

  • 个人主页

Hutool常用工具类整理

阅读数:560次 2023-07-04
字数统计: 6.5k字   |   阅读时长≈ 35分

前言

       Hutool中提供了许多封装好的工具类,本人整理了下web项目中常用的一些工具类和方法,更多详细的用法直接点击跳转官方文档查阅。

1.IO流工具-IoUtil,FileUtil

readLines-按行读取
close-关闭流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Test
@DisplayName("IO流工具-IoUtil")
public void ioUtilTest() {
// 读取磁盘文件
File file1 = new File("D:/test1.txt");
File file2 = new File("D:/test2.txt");
// 获取文件读取字符流
InputStream in1 = FileUtil.getInputStream(file1);
InputStream in2 = FileUtil.getInputStream(file2);
List<String> listText1 = new ArrayList<>();
List<String> listText2 = new ArrayList<>();
try {
// 可指定字符集编码读取流中内容
IoUtil.readLines(in1, StandardCharsets.UTF_8, listText1);
// 固定以UTF-8字符集编码读取流中内容
IoUtil.readUtf8Lines(in2, listText2);
} catch (Exception e) {
log.error("读取文件内容失败", e);
} finally {
// 关闭流
IoUtil.close(in1);
IoUtil.close(in2);
}
log.info("test1.text 内容: {}", listText1);
log.info("test2.text 内容: {}", listText2);
}

执行结果:

1
2
10:57:23.174 [main] INFO common.HutoolTest - test1.text 内容: [红豆生南国,, 春来发几枝。, 愿君多采撷,, 此物最相思。]
10:57:23.183 [main] INFO common.HutoolTest - test2.text 内容: [千山鸟飞绝,, 万径人踪灭。, 孤舟蓑笠翁,, 独钓寒江雪。]

2.对象工具-ObjectUtil

defaultIfNull-默认值
equals-比较两个对象是否相等
isNull isNotNull isEmpty isNotEmpty-判空
isBasicType-判断对象是否为基础类型
clone cloneIfPossible-克隆对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@Test
@DisplayName("对象工具-ObjectUtil")
public void objectUtilTest() {
log.info("*****************1.默认值******************");
// 1.默认值,替代三目运算
LocalDate date = null;
// 此处判断如果date不为null,则调用date.toString; data为null,默认值为null
String dateStr1 = ObjectUtil.defaultIfNull(date, LocalDate::toString, null);
date = LocalDate.now();
String dateStr2 = ObjectUtil.defaultIfNull(date, LocalDate::toString, null);

log.info("dateStr1: {}", dateStr1);
log.info("dateStr2: {}", dateStr2);

log.info("*****************2.比较两个对象是否相等******************");
// 2.比较两个对象是否相等, 替代a.equals(b),避免a为null,造成不必要的NPE
Integer a = 1234;
Integer b = 1234;
boolean equals1 = ObjectUtil.equals(a, b);
log.info("equals1: {}, a={}, b={}", equals1, a, b);
a = null;
boolean equals2 = ObjectUtil.equals(a, b);
log.info("equals2: {}, a={}, b={}", equals2, a, b);
b = null;
boolean equals3 = ObjectUtil.equals(a, b);
log.info("equals3: {}, a={}, b={}", equals3, a, b);

log.info("*****************3.判空******************");
// 3.判空,isNull等价于a == null; isEmpty能根据类型判空,是集合,map,数组对象会判断,size=0为空
List<String> list = null;
boolean isNull = ObjectUtil.isNull(list);
log.info("isNull: {}, list={}", isNull, list);
list = CollUtil.newArrayList();
boolean isEmpty = ObjectUtil.isEmpty(list);
log.info("isEmpty: {}, list={}", isEmpty, list);
boolean isNotNull = ObjectUtil.isNotNull(list);
log.info("isNotNull: {}, list={}", isNotNull, list);
list.add("test");
boolean isNotEmpty = ObjectUtil.isNotEmpty(list);
log.info("isNotEmpty: {}, list={}", isNotEmpty, list);

log.info("*****************4.判断对象是否为基础类型******************");
// 4.判断对象是否为基础类型
// 包装类型 Boolean Byte Character Double Float Integer Long Short
// 原始类型 boolean byte char double float int long short
Number x = 0;
String y = "0";
List<String> z = CollUtil.newArrayList("0");
boolean isBasicType1 = ObjectUtil.isBasicType(x);
log.info("isBasicType1: {}, x={}", isBasicType1, x);
boolean isBasicType2 = ObjectUtil.isBasicType(y);
log.info("isBasicType2: {}, y={}", isBasicType2, y);
boolean isBasicType3 = ObjectUtil.isBasicType(z);
log.info("isBasicType3: {}, z={}", isBasicType3, z);

log.info("*****************5.克隆对象******************");
// 5.克隆对象
List<Integer> source = CollUtil.newArrayList(1, 2, 3);
log.info("source: {}", source);
List<Integer> target1 = ObjectUtil.clone(source);
log.info("target1: {}", target1);
List<Integer> target2 = ObjectUtil.cloneIfPossible(source);
log.info("target2: {}", target2);
Assertions.assertEquals(source, target1);
Assertions.assertEquals(source, target2);
}

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
15:01:06.520 [main] INFO common.HutoolTest - *****************1.默认值******************
15:01:06.546 [main] INFO common.HutoolTest - dateStr1: null
15:01:06.550 [main] INFO common.HutoolTest - dateStr2: 2023-07-04
15:01:06.550 [main] INFO common.HutoolTest - *****************2.比较两个对象是否相等******************
15:01:06.555 [main] INFO common.HutoolTest - equals1: true, a=1234, b=1234
15:01:06.556 [main] INFO common.HutoolTest - equals2: false, a=null, b=1234
15:01:06.556 [main] INFO common.HutoolTest - equals3: true, a=null, b=null
15:01:06.556 [main] INFO common.HutoolTest - *****************3.判空******************
15:01:06.556 [main] INFO common.HutoolTest - isNull: true, list=null
15:01:06.577 [main] INFO common.HutoolTest - isEmpty: true, list=[]
15:01:06.577 [main] INFO common.HutoolTest - isNotNull: true, list=[]
15:01:06.578 [main] INFO common.HutoolTest - isNotEmpty: true, list=[test]
15:01:06.578 [main] INFO common.HutoolTest - *****************4.判断对象是否为基础类型******************
15:01:06.582 [main] INFO common.HutoolTest - isBasicType1: true, x=0
15:01:06.582 [main] INFO common.HutoolTest - isBasicType2: false, y=0
15:01:06.582 [main] INFO common.HutoolTest - isBasicType3: false, z=[0]
15:01:06.582 [main] INFO common.HutoolTest - *****************5.克隆对象******************
15:01:11.654 [main] INFO common.HutoolTest - source: [1, 2, 3]
15:01:11.671 [main] INFO common.HutoolTest - target1: [1, 2, 3]
15:01:11.671 [main] INFO common.HutoolTest - target2: [1, 2, 3]

3.集合、Map和数组工具-CollUtil,ListUtil,MapUtil,ArrayUtil

isEmpty,isNotEmpty和defaultIfEmpty-判空和默认值方法几个工具类都有就不一一举例了

CollUtil

newArrayList-初始化一个可变集合
join-集合转换为拼接字符串
sortPageAll

1
2
3
4
5
6
7
8
9
10
11
// CollUtil.newArrayList返回的list支持修改,Arrays.asList返回的list继承了AbstractList,不可修改
List<String> list = CollUtil.newArrayList("a", "b", "c");
// 集合拼接转字符串
String join = CollUtil.join(list, StrUtil.COMMA);
log.info("join: {}, list={}", join, list);
// 合并多个list,返回排序分页的结果
List<Integer> list1 = CollUtil.newArrayList(1, 4, 7);
List<Integer> list2 = CollUtil.newArrayList(2, 5, 8);
List<Integer> list3 = CollUtil.newArrayList(3, 6, 9);
List<Integer> sortPageAll = CollUtil.sortPageAll(0, 5, Comparator.naturalOrder() , list1, list2, list3);
log.info("sortPageAll: {}", sortPageAll);

执行结果:

1
2
14:47:33.974 [main] INFO common.HutoolTest - join: a,b,c, list=[a, b, c]
14:47:33.992 [main] INFO common.HutoolTest - sortPageAll: [1, 2, 3, 4, 5]

ListUtil

of-初始化UnmodifiableRandomAccessList集合
toList-初始化ArrayList集合
toLinkedList-初始化LinkedList集合
unmodifiable-构建不可修改集合
reverse reverseNew-反转集合
sortByPinyin-拼音排序集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Test
@DisplayName("集合工具-ListUtil")
public void listUtilTest() {
// 初始化返回UnmodifiableRandomAccessList不可修改集合
List<String> list1 = ListUtil.of("a", "b", "c");
log.info("list1: {}, class={}", list1, list1.getClass());

// 初始化返回ArrayList可修改集合
List<String> list2 = ListUtil.toList("a", "b", "c");
log.info("list2: {}, class={}", list2, list2.getClass());

// 初始化返回LinkedList可修改集合
List<String> list3 = ListUtil.toLinkedList("a", "b", "c");
log.info("list3: {}, class={}", list3, list3.getClass());

// 构建不可修改集合
List<String> list4 = ListUtil.unmodifiable(list2);
log.info("list4: {}, class={}", list4, list4.getClass());

// 反转集合-原始集合反转
List<String> list5 = ListUtil.reverse(list2);
log.info("list5: {}, class={}; list2: {}", list5, list5.getClass(), list2);

// 反转集合-原始集合不反转
List<String> list6 = ListUtil.reverseNew(list3);
log.info("list6: {}, class={}; list3: {}", list6, list6.getClass(), list3);

// 根据汉语拼音排序(目前不支持多音字识别,如重庆)
List<String> cities = ListUtil.toLinkedList("上海", "北京", "武汉", "深圳");
log.info("cities sort before: {}", cities);
ListUtil.sortByPinyin(cities);
log.info("cities sort after: {}", cities);
}

执行结果:

1
2
3
4
5
6
7
8
15:35:38.478 [main] INFO common.HutoolTest - list1: [a, b, c], class=class java.util.Collections$UnmodifiableRandomAccessList
15:35:38.489 [main] INFO common.HutoolTest - list2: [a, b, c], class=class java.util.ArrayList
15:35:38.489 [main] INFO common.HutoolTest - list3: [a, b, c], class=class java.util.LinkedList
15:35:38.490 [main] INFO common.HutoolTest - list4: [a, b, c], class=class java.util.Collections$UnmodifiableRandomAccessList
15:35:38.490 [main] INFO common.HutoolTest - list5: [c, b, a], class=class java.util.ArrayList; list2: [c, b, a]
15:35:38.527 [main] INFO common.HutoolTest - list6: [c, b, a], class=class java.util.LinkedList; list3: [a, b, c]
15:35:38.527 [main] INFO common.HutoolTest - cities sort before: [上海, 北京, 武汉, 深圳]
15:35:38.583 [main] INFO common.HutoolTest - cities sort after: [北京, 上海, 深圳, 武汉]

MapUtil

newHashMap-初始化Map
join-map拼接成字符串
reverse-键和值互换
toListMap-行转列
toMapList-列转行
getKey-根据值获取键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Test
@DisplayName("Map工具-MapUtil")
public void mapUtilTest() {
// 初始化Map
Map<String, String> map = MapUtil.newHashMap(16, true);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
log.info("map: {}", map);
// map拼接
String join = MapUtil.join(map, StrUtil.COMMA, StrUtil.DASHED);
log.info("join: {}", join);
// 键和值互换 - 键和值的类型必须相同
Map<String, String> reversedMap = MapUtil.reverse(map);
log.info("reversedMap: {}", reversedMap);
// 行转列
List<Map<String, String>> list = new ArrayList<>();
list.add(map);
Map<String, List<String>> listMap = MapUtil.toListMap(list);
log.info("source: {}, listMap: {}", list, listMap);
// 列转行
List<Map<String, String>> mapList = MapUtil.toMapList(listMap);
log.info("source: {}, mapList: {}", listMap, mapList);
// 双向查找Map
BiMap<String, Integer> biMap = new BiMap<>(new HashMap<>());
biMap.put("a", 1);
Integer value = biMap.get("a");
String key = biMap.getKey(1);
log.info("biMap: {}; key={}, value={}", biMap, key, value);
}

执行结果:

1
2
3
4
5
6
16:32:07.895 [main] INFO common.HutoolTest - map: {a=1, b=2, c=3}
16:32:07.952 [main] INFO common.HutoolTest - join: a-1,b-2,c-3
16:32:07.968 [main] INFO common.HutoolTest - reversedMap: {1=a, 2=b, 3=c}
16:32:07.975 [main] INFO common.HutoolTest - source: [{a=1, b=2, c=3}], listMap: {a=[1], b=[2], c=[3]}
16:32:07.975 [main] INFO common.HutoolTest - source: {a=[1], b=[2], c=[3]}, mapList: [{a=1, b=2, c=3}]
16:32:07.978 [main] INFO common.HutoolTest - biMap: {a=1}; key=a, value=1

ArrayUtil

isArray-是否为数组
join-数组拼接字符串
toString-数组toString
contains-包含元素判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
@DisplayName("数组工具-ArrayUtil")
public void arrayUtilTest() {
// 判断对象是否为数组
int[] a = new int[] {1,2,3};
boolean isArray = ArrayUtil.isArray(a);
log.info("isArray: {}, a={}", isArray, a);
// 数组拼接
String join = ArrayUtil.join(a, StrUtil.COMMA);
log.info("join: {}, a={}", join, a);
// 数组toString
log.info("toString: {}, a={}", ArrayUtil.toString(a), a.toString());
// 包含元素判断
boolean contains = ArrayUtil.contains(a, 1);
log.info("contains: {}, a={}", contains, a);
}

执行结果:

1
2
3
4
17:12:59.713 [main] INFO common.HutoolTest - isArray: true, a=[1, 2, 3]
17:12:59.758 [main] INFO common.HutoolTest - join: 1,2,3, a=[1, 2, 3]
17:12:59.758 [main] INFO common.HutoolTest - toString: [1, 2, 3], a=[I@928763c
17:12:59.758 [main] INFO common.HutoolTest - contains: true, a=[1, 2, 3]

4.字符串工具-StrUtil

reverse-反转字符串
format-format方法 与sl4j用法完全一样
addSuffixIfNot commonSuffix endWithAnyIgnoreCase removeSuffixIgnoreCase- 后缀相关处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
@DisplayName("字符串工具-StrUtil")
public void strUtilTest() {
// 反转字符串
String reverse = StrUtil.reverse("abc");
log.info("reverse: {}", reverse);
// format方法 与sl4j用法完全一样
String template = "x={}, y={}";
String result = StrUtil.format(template, "a+b", "c+d");
log.info("result: {}", result);
// 后缀相关处理
String pic1 = StrUtil.addSuffixIfNot("图片1", ".jpg");
String pic2 = StrUtil.addSuffixIfNot("图片2", ".jpg");
String commonSuffix = StrUtil.commonSuffix(pic1, pic2).toString();
boolean isPicture = StrUtil.endWithAnyIgnoreCase(pic1, ".jpg", ".png");
String fileName = StrUtil.removeSuffixIgnoreCase(pic1, ".JPG");
log.info("pic1={}, pic2={}, comonSuffix: {}, isPicture: {}, fileName: {}", pic1, pic2, commonSuffix, isPicture, fileName);
}

执行结果:

1
2
3
17:49:39.296 [main] INFO common.HutoolTest - reverse: cba
17:49:39.305 [main] INFO common.HutoolTest - result: x=a+b, y=c+d
17:49:39.305 [main] INFO common.HutoolTest - pic1=图片1.jpg, pic2=图片2.jpg, comonSuffix: .jpg, isPicture: true, fileName: 图片1

5.Bean工具-BeanUtil

isBean-是否为Bean对象
toBean-map转bean
beanToMap-bean转map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
@DisplayName("Bean工具-BeanUtil")
public void beanUtilTest() {
// 是否为Bean对象
List<String> obj = new ArrayList<>();
boolean isBean = BeanUtil.isBean(obj.getClass());
log.info("isBean: {}" , isBean);
// mapToBean
Map<String, Object> sourceMap = MapUtil.newHashMap(2);
sourceMap.put("name", "张三");
sourceMap.put("age", 18);
Person person = BeanUtil.toBean(sourceMap, Person.class);
log.info("sourceMap: {}, bean: {}", sourceMap, person);
// beanToMap
Map<String, Object> targetMap = BeanUtil.beanToMap(person);
log.info("bean: {}, targetMap: {}", person, targetMap);
}

@Data
static class Person {
private String name;
private Integer age;
}

执行结果:

1
2
3
18:10:01.223 [main] INFO common.HutoolTest - isBean: false
18:10:01.344 [main] INFO common.HutoolTest - sourceMap: {name=张三, age=18}, bean: HutoolTest.Person(name=张三, age=18)
18:10:01.347 [main] INFO common.HutoolTest - bean: HutoolTest.Person(name=张三, age=18), targetMap: {name=张三, age=18}

6.类型转换工具-Convert

toStr-转换成字符串
toIntArray-转换为指定类型数组
toDate-转换为日期对象
toList-转换为集合
convertTime-时间单位转换
digitToChinese-额大小写转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Test
@DisplayName("类型转换工具-Convert")
public void convertTest() {
// 转换成字符串
int a = 1;
String aStr = Convert.toStr(a);
log.info("aStr: {}", aStr);
String[] b = { "1", "2", "3", "4" };
String bStr = Convert.toStr(b);
log.info("bStr: {}, b={}", bStr, b);
// 转换为指定类型数组
Integer[] intArray = Convert.toIntArray(b);
log.info("intArray: {}, b={}", intArray, b);
// 转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
log.info("date: {}", date);
// 转换为集合
Object[] array = {"a", "b", "c", 1, 2};
List<?> list = Convert.toList(array);
log.info("list: {}, array={}", list, array);
// 时间单位转换
long ms = 4535345;
long min = Convert.convertTime(ms, TimeUnit.MILLISECONDS, TimeUnit.MINUTES);
log.info("min: {}", min);
Assertions.assertEquals(ms /(60*1000), min);
// 金额大小写转换
Double digit = 67556.32;
String digitUppercase = Convert.digitToChinese(digit);
log.info("digitUppercase: {}, digit={}", digitUppercase, digit);
}

执行结果:

1
2
3
4
5
6
7
21:35:40.676 [main] INFO common.HutoolTest - aStr: 1
21:35:40.682 [main] INFO common.HutoolTest - bStr: [1, 2, 3, 4], b=[1, 2, 3, 4]
21:35:40.693 [main] INFO common.HutoolTest - intArray: [1, 2, 3, 4], b=[1, 2, 3, 4]
21:35:40.799 [main] INFO common.HutoolTest - date: Sat May 06 00:00:00 CST 2017
21:35:40.802 [main] INFO common.HutoolTest - list: [a, b, c, 1, 2], array=[a, b, c, 1, 2]
21:35:40.802 [main] INFO common.HutoolTest - min: 75
21:35:40.814 [main] INFO common.HutoolTest - digitUppercase: 陆万柒仟伍佰伍拾陆元叁角贰分, digit=67556.32

7.字段验证器-Validator

isEmail-邮箱校验
isIpv4-Ipv4校验
isUrl-url校验
isCreditCode-统一社会信用代码校验
isUUID-UUID校验
isLetter-字母校验
isChinese-中文校验
isNumber-数字校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Test
@DisplayName("字段验证器-Validator")
public void validatorTest() {
// 邮箱校验
boolean isEmail = Validator.isEmail("loolly@gmail.com");
log.info("isEmail: {}", isEmail);
// Ipv4校验
boolean isIpv4 = Validator.isIpv4("172.17.225.8");
log.info("isIpv4: {}", isIpv4);
// url校验
boolean isUrl = Validator.isUrl("https://yinshuang.gitee.io");
log.info("isUrl: {}", isUrl);
// 统一社会信用代码校验
boolean isCreditCode = Validator.isCreditCode("911100000918666422");
log.info("isCreditCode: {}", isCreditCode);
// UUID校验
boolean isUUID = Validator.isUUID(IdUtil.fastUUID());
log.info("isUUID: {}", isUUID);
// 字母校验
boolean isLetter = Validator.isLetter("abc");
log.info("isLetter: {}", isLetter);
// 中文校验
boolean isChinese = Validator.isChinese("中文");
log.info("isChinese: {}", isChinese);
// 数字校验
boolean isNumber = Validator.isNumber("1.004e5");
log.info("isNumber: {}", isNumber);
}

执行结果:

1
2
3
4
5
6
7
8
22:19:10.655 [main] INFO common.HutoolTest - isEmail: true
22:19:10.661 [main] INFO common.HutoolTest - isIpv4: true
22:19:10.666 [main] INFO common.HutoolTest - isUrl: true
22:19:10.667 [main] INFO common.HutoolTest - isCreditCode: true
22:19:10.672 [main] INFO common.HutoolTest - isUUID: true
22:19:10.674 [main] INFO common.HutoolTest - isLetter: true
22:19:10.675 [main] INFO common.HutoolTest - isChinese: true
22:19:10.677 [main] INFO common.HutoolTest - isNumber: true

8.正则工具-ReUtil

isMatch-是否匹配给定正则
contains-是否包含给定正则的字符串
findAll-查找所有匹配文本
getFirstNumber-找到匹配的第一个数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
@DisplayName("正则工具-ReUtil")
public void reUtilTest() {
// 是否匹配给定正则
String content = "ZZZaaabbbccc中文1234";
boolean isMatch = ReUtil.isMatch("\\w+[\u4E00-\u9FFF]+\\d+", content);
log.info("isMatch: {}", isMatch);
Assertions.assertTrue(isMatch);
// 是否包含给定正则的字符串
boolean contains = ReUtil.contains("[\u4E00-\u9FFF]+", content);
log.info("contains: {}", contains);
Assertions.assertTrue(contains);
// 查找所有匹配文本
List<String> resultFindAll = ReUtil.findAll("\\w{2}", content, 0, new ArrayList<>());
log.info("resultFindAll: {}", resultFindAll);
// 找到匹配的第一个数字
Integer resultGetFirstNumber = ReUtil.getFirstNumber(content);
log.info("resultGetFirstNumber: {}", resultGetFirstNumber);
}

执行结果:

1
2
3
4
22:37:10.223 [main] INFO common.HutoolTest - isMatch: true
22:37:10.233 [main] INFO common.HutoolTest - contains: true
22:37:10.236 [main] INFO common.HutoolTest - resultFindAll: [ZZ, Za, aa, bb, bc, cc, 12, 34]
22:37:10.275 [main] INFO common.HutoolTest - resultGetFirstNumber: 1234

9.日期时间工具-DateUtil

now today-当前时间、当前日期
parse format formatDate … -格式化输出日期
offset yesterday lastWeek … - 日期时间偏移
between-日期时间差
getZodiac-星座
getChineseZodiac-属相
ageOfNow-年龄
isLeapYear-是否闰年

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@Test
@DisplayName("日期时间工具-DateUtil")
public void dateUtilTest() {
log.info("****************当前时间*****************");
// 当前时间字符串,格式:yyyy-MM-dd HH:mm:ss
String nowStr = DateUtil.now();
log.info("nowStr: {}", nowStr);
// 当前日期字符串,格式:yyyy-MM-dd
String todayStr = DateUtil.today();
log.info("todayStr: {}", todayStr);
// 当前日期
Calendar calendar = Calendar.getInstance();
Date now = DateUtil.date(calendar);
log.info("now: {}", now);

log.info("****************格式化日期输出*****************");
// 格式化日期输出
String dateStr = "1998-03-01";
Date date = DateUtil.parse(dateStr);

log.info("date: {}", date);
String format = DateUtil.format(date, "yyyy/MM/dd");
log.info("format: {}", format);
String formatDate = DateUtil.formatDate(date);
log.info("formatDate: {}", formatDate);
String formatDateTime = DateUtil.formatDateTime(date);
log.info("formatDateTime: {}", formatDateTime);
String formatTime = DateUtil.formatTime(date);
log.info("formatTime: {}", formatTime);

log.info("****************日期时间偏移、日期时间差*****************");
// 日期时间偏移
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
log.info("newDate: {}", newDate);
Date yesterday = DateUtil.yesterday();
log.info("yesterday: {}", yesterday);
Date lastWeek = DateUtil.lastWeek();
log.info("lastWeek: {}", lastWeek);
Date lastMonth = DateUtil.lastMonth();
log.info("lastMonth: {}", lastMonth);
// 日期时间差
long betweenDay = DateUtil.between(lastMonth, lastWeek, DateUnit.DAY);
log.info("betweenDay: {}", betweenDay);

log.info("****************星座、属相、年龄和闰年计算*****************");
// 星座
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
String zodiac = DateUtil.getZodiac(month, day);
log.info("zodiac: {}, calendar={}, month={}, day={}", zodiac, DateUtil.date(calendar), month+1, day);
// 属相
int year = calendar.get(Calendar.YEAR);
String chineseZodiac = DateUtil.getChineseZodiac(year);
log.info("chineseZodiac: {}, year={}", chineseZodiac, year);
// 年龄
int age = DateUtil.ageOfNow(dateStr);
log.info("age: {}, date={}", age, dateStr);
// 是否闰年
boolean isLeapYear = DateUtil.isLeapYear(year);
log.info("isLeapYear: {}, year={}", isLeapYear, year);
}

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22:01:38.392 [main] INFO common.HutoolTest - ****************当前时间*****************
22:01:38.511 [main] INFO common.HutoolTest - nowStr: 2023-07-26 22:01:38
22:01:38.512 [main] INFO common.HutoolTest - todayStr: 2023-07-26
22:01:38.512 [main] INFO common.HutoolTest - now: 2023-07-26 22:01:38
22:01:38.513 [main] INFO common.HutoolTest - ****************格式化日期输出*****************
22:01:38.533 [main] INFO common.HutoolTest - date: 1998-03-01 00:00:00
22:01:38.535 [main] INFO common.HutoolTest - format: 1998/03/01
22:01:38.535 [main] INFO common.HutoolTest - formatDate: 1998-03-01
22:01:38.535 [main] INFO common.HutoolTest - formatDateTime: 1998-03-01 00:00:00
22:01:38.535 [main] INFO common.HutoolTest - formatTime: 00:00:00
22:01:38.535 [main] INFO common.HutoolTest - ****************日期时间偏移、日期时间差*****************
22:01:38.535 [main] INFO common.HutoolTest - newDate: 1998-03-03 00:00:00
22:01:38.536 [main] INFO common.HutoolTest - yesterday: 2023-07-25 22:01:38
22:01:38.536 [main] INFO common.HutoolTest - lastWeek: 2023-07-19 22:01:38
22:01:38.536 [main] INFO common.HutoolTest - lastMonth: 2023-06-26 22:01:38
22:01:38.537 [main] INFO common.HutoolTest - betweenDay: 23
22:01:38.537 [main] INFO common.HutoolTest - ****************星座、属相、年龄和闰年计算*****************
22:01:38.538 [main] INFO common.HutoolTest - zodiac: 狮子座, calendar=2023-07-26 22:01:38, month=7, day=26
22:01:38.538 [main] INFO common.HutoolTest - chineseZodiac: 兔, year=2023
22:01:38.539 [main] INFO common.HutoolTest - age: 25, date=1998-03-01
22:01:38.539 [main] INFO common.HutoolTest - isLeapYear: false, year=2023

10.数学相关工具-NumberUtil,MathUtil

NumberUtil

isNumber-是否为数字
isInteger-是否为整数
isDouble-是否为浮点数
isPrimes-是否为质数
decimalFormat-数字格式化
add sub mul div-四则运算(解决float和double类型无法进行精确计算的问题)
factorial-阶乘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@Test
@DisplayName("数字工具-NumberUtil")
public void numberUtil() {
log.info("****************是否为数字*****************");
// 是否为数字
String doubleStr = "1.003e-3";
String primesStr = "53";
boolean isNumber = NumberUtil.isNumber(doubleStr);
log.info("isNumber: {}", isNumber);
// 是否为整数
boolean isInteger = NumberUtil.isInteger(primesStr);
log.info("isInteger: {}", isInteger);
// 是否为浮点数
boolean isDouble = NumberUtil.isDouble(doubleStr);
log.info("isDouble: {}", isDouble);
// 是否为质数
boolean isPrimes = NumberUtil.isPrimes(Integer.parseInt(primesStr));
log.info("isPrimes: {}", isPrimes);

log.info("****************数字格式化*****************");
// 格式中主要以 # 和 0 两种占位符号来指定数字长度。0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置。
long c = 299792458;
double exp = Math.E;
double pi = Math.PI;
double ratio = exp/pi;
double d = 1.200;
// 每三位以逗号进行分隔
String cFormat = NumberUtil.decimalFormat(",###", c);
log.info("cFormat: {}, c={}", cFormat, c);
// 显示为科学计数法,取三位小数
String expFormat = NumberUtil.decimalFormat("#.###E0", exp);
log.info("expFormat: {}, exp={}", expFormat, exp);
// 取两位小数
String piFormat = NumberUtil.decimalFormat("#.##", pi);
log.info("piFormat: {}, pi={}", piFormat, pi);
// 以百分比方式计数,取两位小数
String ratioFormat = NumberUtil.decimalFormat("#.##%", ratio);
log.info("ratioFormat: {}, ratio={}", ratioFormat, ratio);
// 数字转字符串,自动并去除尾小数点儿后多余的0
String dStr = NumberUtil.toStr(d);
log.info("dStr: {}, d={}", dStr, d);

log.info("****************四则运算*****************");
// 以下四种运算都会将double转为BigDecimal后计算,解决float和double类型无法进行精确计算的问题。 (如0.1+0.2精度丢失问题)
double x = 0.1;
double y = 0.2;
double m = 20;
double n = 0.07;
// 加法
double add = NumberUtil.add(x, y);
log.info("add: {}, x+y={}", add, x+y);
// 减法
double sub = NumberUtil.sub(x, y);
log.info("sub: {}, x-y={}", sub, x-y);
// 乘法
double mul = NumberUtil.mul(m, n);
log.info("mul: {}, m*n={}", mul, m*n);
// 除法 (默认保留10位小数,可以指定保留位数)
BigDecimal bigM = new BigDecimal(m);
BigDecimal bigN = new BigDecimal(n);
BigDecimal div1 = NumberUtil.div(bigM, bigN);
BigDecimal div2 = NumberUtil.div(bigM, bigN, 18);
log.info("div1: {}, div2: {}, m/n={}", div1, div2, m/n);
// 阶乘 5!
long f5 = NumberUtil.factorial(5);
log.info("5! = {}", f5);
}

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
22:06:17.108 [main] INFO common.HutoolTest - ****************是否为数字*****************
22:06:17.120 [main] INFO common.HutoolTest - isNumber: true
22:06:17.122 [main] INFO common.HutoolTest - isInteger: true
22:06:17.122 [main] INFO common.HutoolTest - isDouble: true
22:06:17.124 [main] INFO common.HutoolTest - isPrimes: true
22:06:17.124 [main] INFO common.HutoolTest - ****************数字格式化*****************
22:06:17.124 [main] INFO common.HutoolTest - cFormat: 299,792,458, c=299792458
22:06:17.125 [main] INFO common.HutoolTest - expFormat: 2.718E0, exp=2.718281828459045
22:06:17.125 [main] INFO common.HutoolTest - piFormat: 3.14, pi=3.141592653589793
22:06:17.126 [main] INFO common.HutoolTest - ratioFormat: 86.53%, ratio=0.8652559794322651
22:06:17.126 [main] INFO common.HutoolTest - dStr: 1.2, d=1.2
22:06:17.126 [main] INFO common.HutoolTest - ****************四则运算*****************
22:06:17.131 [main] INFO common.HutoolTest - add: 0.3, x+y=0.30000000000000004
22:06:17.131 [main] INFO common.HutoolTest - sub: -0.1, x-y=-0.1
22:06:17.133 [main] INFO common.HutoolTest - mul: 1.4, m*n=1.4000000000000001
22:06:17.133 [main] INFO common.HutoolTest - div1: 285.7142857143, div2: 285.714285714285687097, m/n=285.71428571428567
22:06:17.133 [main] INFO common.HutoolTest - 5! = 120

MathUtil

arrangementCount-计算排列数
arrangementSelect-排列选择(从列表中选择n个排列)
combinationCount-计算组合数
combinationSelect-组合选择(从列表中选择n个组合)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
@DisplayName("数学工具-MathUtil")
public void mathUtil() {
String[] team = ListUtil.toList("BLG", "JDG", "TES", "LNG", "EDG", "WBG").toArray(new String[0]);
int m = 6;
int n = 2;
// 排列
// 场景1:6只LPL队伍进行双循环比赛 A(m,n) = m!/(m-n)!
long matchesCount1 = MathUtil.arrangementCount(m, n);
long Amn = NumberUtil.factorial(m)/NumberUtil.factorial(m-n);
List<String[]> matchesList1 = MathUtil.arrangementSelect(team, 2);
List<String> matchesListStr1 = matchesList1.stream().map(t -> ArrayUtil.join(t, " vs ")).collect(Collectors.toList());
log.info("matchesCount1: {}, A(m,n)={}", matchesCount1, Amn);
log.info("matchesList1: {}", matchesListStr1);
// 组合
// 场景2:6只LPL队伍进行单循环比赛 C(m,n) = m!/((m-n)!*n!)
long matchesCount2 = MathUtil.combinationCount(m, n);
long Cmn = NumberUtil.factorial(m)/(NumberUtil.factorial(m-n)*NumberUtil.factorial(n));
List<String[]> matchesList2 = MathUtil.combinationSelect(team, 2);
List<String> matchesListStr2 = matchesList2.stream().map(t -> ArrayUtil.join(t, " vs ")).collect(Collectors.toList());
log.info("matchesCount2: {}, C(m,n)={}", matchesCount2, Cmn);
log.info("matchesList2: {}", matchesListStr2);
}

执行结果:

1
2
3
4
22:07:12.414 [main] INFO common.HutoolTest - matchesCount1: 30, A(m,n)=30
22:07:12.420 [main] INFO common.HutoolTest - matchesList1: [BLG vs JDG, BLG vs TES, BLG vs LNG, BLG vs EDG, BLG vs WBG, JDG vs BLG, JDG vs TES, JDG vs LNG, JDG vs EDG, JDG vs WBG, TES vs BLG, TES vs JDG, TES vs LNG, TES vs EDG, TES vs WBG, LNG vs BLG, LNG vs JDG, LNG vs TES, LNG vs EDG, LNG vs WBG, EDG vs BLG, EDG vs JDG, EDG vs TES, EDG vs LNG, EDG vs WBG, WBG vs BLG, WBG vs JDG, WBG vs TES, WBG vs LNG, WBG vs EDG]
22:07:12.424 [main] INFO common.HutoolTest - matchesCount2: 15, C(m,n)=15
22:07:12.424 [main] INFO common.HutoolTest - matchesList2: [BLG vs JDG, BLG vs TES, BLG vs LNG, BLG vs EDG, BLG vs WBG, JDG vs TES, JDG vs LNG, JDG vs EDG, JDG vs WBG, TES vs LNG, TES vs EDG, TES vs WBG, LNG vs EDG, LNG vs WBG, EDG vs WBG]

11.Http工具-HttpUtil

isHttps isHttp-判断Url是否https,http
get-GET请求
post-POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
@DisplayName("Http工具-HttpUtil")
public void httpUtil() {
// 判断Url是否https
String url = "https://www.baidu.com";
boolean isHttps = HttpUtil.isHttps(url);
boolean isHttp = HttpUtil.isHttp(url);
log.info("isHttps: {}, isHttp: {}", isHttps, isHttp);
// GET请求
String getRequest = HttpUtil.get(url);
log.info("getRequest: {}", getRequest.subSequence(0, 50));
// POST请求
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");
String postRequest = HttpUtil.post(url, paramMap);
log.info("postRequest: {}", postRequest);
}

执行结果:

1
2
3
4
5
6
7
8
9
22:08:52.414 [main] INFO common.HutoolTest - isHttps: true, isHttp: false
22:08:53.043 [main] INFO common.HutoolTest - getRequest: <!DOCTYPE html><!--STATUS OK--><html><head><meta h
22:08:53.143 [main] INFO common.HutoolTest - postRequest: <html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

12.HTML工具-HtmlUtil

escape-转义HTML特殊字符
unescape-还原被转义的HTML特殊字符
removeHtmlTag-清除指定HTML标签和被标签包围的内容
cleanHtmlTag-清除所有HTML标签,但是保留标签内的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
@DisplayName("HTML工具-HtmlUtil")
public void htmlUtil() {
String html = "<html><body>123'123'</body></html>";
// 转义HTML特殊字符
String escape = HtmlUtil.escape(html);
log.info("escape: {}", escape);
// 还原被转义的HTML特殊字符
String unescape = HtmlUtil.unescape(escape);
log.info("unescape: {}", unescape);
// 清除指定HTML标签和被标签包围的内容
String removeHtmlTag = HtmlUtil.removeHtmlTag(html, "body");
log.info("removeHtmlTag: {}", removeHtmlTag);
// 清除所有HTML标签,但是保留标签内的内容
String cleanHtmlTag = HtmlUtil.cleanHtmlTag(html);
log.info("cleanHtmlTag: {}", cleanHtmlTag);
}

执行结果:

1
2
3
4
22:10:30.589 [main] INFO common.HutoolTest - escape: &lt;html&gt;&lt;body&gt;123&#039;123&#039;&lt;/body&gt;&lt;/html&gt;
22:10:30.612 [main] INFO common.HutoolTest - unescape: <html><body>123'123'</body></html>
22:10:30.646 [main] INFO common.HutoolTest - removeHtmlTag: <html></html>
22:10:30.682 [main] INFO common.HutoolTest - cleanHtmlTag: 123'123'

13.Spring工具-SpringUtil

getBean-获取指定Bean

1
2
3
4
5
6
7
8
9
10
@Test
@DisplayName("Spring工具-SpringUtil")
public void springUtil() {
// 获取Bean 测试类要加@SpringBootTest(Application.class) 模拟springboot启动环境 AliPayHandler 在模块中加了@Component注解会在启动时注入Bean
final AliPayHandler handler1 = SpringUtil.getBean("aliPayHandler");
final AliPayHandler handler2 = SpringUtil.getBean(AliPayHandler.class);
log.info("handler1: {}", handler1);
log.info("handler2: {}", handler2);
Assertions.assertEquals(handler1, handler2);
}

执行结果:

1
2
20:30:31.895  INFO 40615 --- [main] common.HutoolTest  : handler1: com.xxx.handler.AliPayHandler@653fb8d1
20:30:31.895 INFO 40615 --- [main] common.HutoolTest : handler2: com.xxx.handler.AliPayHandler@653fb8d1
赏

谢谢你请我吃糖果

微信
  • 本文作者: yinshuang
  • 本文链接: https://yinshuang007.github.io/2023/07/04/Hutool常用工具类整理/
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!
  • Hutool

扫一扫,分享到微信

AI编程辅助工具分享
SpringBoot中使用mysql8的json类型存储json数据实现CRUD操作
Issue Page
Error: Not Found Project
登录 码云
支持Markdown的样式
Powered by Giteement
© 2021-2025 yinshuang
GitHub:hexo-theme-yilia-plus by Litten
本站总访问量561次 | 本站访客数435人
  • 所有文章
  • 友链
  • 关于我

tag:

  • BitoAI
  • AWS CodeWhisperer
  • CodeGeeX
  • EasyPoi
  • word模板导出
  • MCP
  • FastMcp
  • LangChain
  • CherryStdio
  • OpenMCP
  • Hutool
  • Arthus
  • Mapstruct Plus
  • Jenkins
  • Pipline
  • 企业微信机器人
  • Gitlab webhook
  • MinerU
  • DeepDoc
  • PDF
  • Mysql-json
  • Java函数式编程
  • ApplicationRunner
  • uv
  • python
  • pip
  • conda
  • poi-tl
  • Hutool-StopWatch
  • 工厂模式
  • 策略模式
  • 模板模式
  • 设计模式
  • ThreadLocal
  • TransmittableThreadLocal
  • JetCache
  • Caffeine
  • Redis

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia-plus根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • PDF解析神器MinerU本地部署

    2025-06-22

    #MinerU#DeepDoc#PDF

  • FastMcp框架快速搭建MCP服务

    2025-06-21

    #MCP#FastMcp#LangChain#CherryStdio#OpenMCP

  • poi-tl模板引擎生成word统计图实践

    2025-05-10

    #poi-tl

  • UV快速入门

    2025-04-29

    #uv#python#pip#conda

  • EasyPoi实现word模板导出

    2024-01-25

    #EasyPoi#word模板导出

  • 阿里TransmittableThreadLocal实践

    2023-11-20

    #ThreadLocal#TransmittableThreadLocal

  • 阿里缓存框架JetCache实践

    2023-08-12

    #JetCache#Caffeine#Redis

  • 工厂+策略+模板模式消除代码中的if else

    2023-08-01

    #工厂模式#策略模式#模板模式#设计模式

  • Java类型转换框架MapstructPlus使用分享

    2023-07-19

    #Mapstruct Plus

  • AI编程辅助工具分享

    2023-07-09

    #BitoAI#AWS CodeWhisperer#CodeGeeX

  • Hutool常用工具类整理

    2023-07-04

    #Hutool

  • SpringBoot中使用mysql8的json类型存储json数据实现CRUD操作

    2023-06-11

    #Mysql-json

  • SpringBoot启动常用的初始化加载数据方法

    2023-05-31

    #ApplicationRunner

  • Jenkins流水线任务配置(企业微信机器人通知)

    2023-02-25

    #Jenkins#Pipline#企业微信机器人

  • Jenkins联和Gitlab配置webhook实现push触发自动化部署

    2023-02-20

    #Jenkins#Gitlab webhook

  • 任务耗时统计工具类分享

    2023-02-18

    #Hutool-StopWatch

  • Java应用诊断利器-Arthus

    2023-02-12

    #Arthus

  • TreeUtil组装树工具类分享

    2023-02-05

    #Java函数式编程

  • 个人博客
  • GitHub
  • 码云
主要涉及技术:
Java后端开发


联系QQ:875038467

很惭愧

只做了一点微小的工作
谢谢大家