第三章 Hutool v1.0
第一部分 快速入门
一、简介
1.什么是Hutool
Hutool是一个Java工具包类库,它帮助我们简化每一行代码,减少每一个方法,让Java语言也可以"甜甜的"。Hutool最初是项目中"util"包的整理,后来慢慢积累并演化,形成丰富的工具类库。
2.模块组成
Hutool包含多个模块,可以根据需求单独引入:
| 模块 | 说明 |
|---|---|
| hutool-core | 核心工具类,包括集合、日期、IO、加密等 |
| hutool-aop | AOP切面支持 |
| hutool-bloomFilter | 布隆过滤器 |
| hutool-cache | 缓存实现 |
| hutool-crypto | 加密解密工具 |
| hutool-db | 数据库操作封装 |
| hutool-dfa | DFA自动机 |
| hutool-extra | 扩展工具 |
| hutool-http | HTTP客户端 |
| hutool-log | 日志门面 |
| hutool-script | 脚本执行 |
| hutool-setting | 配置文件工具 |
| hutool-system | 系统调用封装 |
| hutool-json | JSON工具 |
| hutool-captcha | 图片验证码 |
| hutool-poi | POI封装 |
| hutool-word | Word文档操作 |
二、安装配置
1.Maven依赖
xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.25</version>
</dependency>2.Gradle依赖
groovy
implementation 'cn.hutool:hutool-all:5.8.25'第二部分 核心功能(hutool-core)
一、字符串工具(StrUtil)
1.常用方法
java
import cn.hutool.core.util.StrUtil;
// 判断字符串是否为空
StrUtil.isEmpty(null); // true
StrUtil.isEmpty(""); // true
StrUtil.isEmpty(" "); // false
StrUtil.hasEmpty("ab", "cd", ""); // true
// 去除字符串空格
StrUtil.trim(" abc "); // "abc"
StrUtil.trimToNull(" "); // null
StrUtil.trimToEmpty(null); // ""
// 字符串格式化
StrUtil.format("Hello {}!", "World"); // "Hello World!"
StrUtil.format("{} is {}", "Tom", 18); // "Tom is 18"
// 下划线转驼峰
StrUtil.toCamelCase("user_name"); // "userName"
StrUtil.toUnderlineCase("userName"); // "user_name"2.更多方法
java
// 截取字符串
StrUtil.sub("abcdef", 2, 4); // "cd"
StrUtil.subAfter("a.b.c", ".", true); // "b.c"
StrUtil.subBefore("a.b.c", ".", true); // "a.b"
// 判断是否包含
StrUtil.contains("abc", "a"); // true
StrUtil.containsAny("abc", "a", "x"); // true
StrUtil.containsIgnoreCase("ABC", "a"); // true二、日期时间工具(DateUtil)
1.日期格式化
java
import cn.hutool.core.date.DateUtil;
// 当前时间
Date date = DateUtil.date();
String now = DateUtil.now();
String today = DateUtil.today();
// 字符串转日期
Date date = DateUtil.parse("2024-01-01");
Date date = DateUtil.parse("2024-01-01 12:00:00");
// 日期格式化
String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
String format = DateUtil.formatDate(date);
String format = DateUtil.formatTime(date);2.日期计算
java
// 日期偏移
DateTime dateTime = DateUtil.offsetDay(date, 3); // 3天后
DateTime dateTime = DateUtil.offsetHour(date, -2); // 2小时前
DateTime dateTime = DateUtil.offsetMonth(date, 1); // 1个月后
// 日期间隔
long between = DateUtil.between(date1, date2, DateUnit.DAY); // 相差天数
long between = DateUtil.between(date1, date2, DateUnit.HOUR); // 相差小时
// 星期几
int dayOfWeek = DateUtil.dayOfWeek(date); // 1-7(周日为1)
// 是否闰年
boolean leapYear = DateUtil.isLeapYear(2024);3.农历日期
java
// 获取农历日期
String lunar = DateUtil.lunar(date);三、集合工具(CollUtil)
1.集合创建
java
import cn.hutool.core.collection.CollUtil;
// 创建集合
List<String> list = CollUtil.newArrayList("a", "b", "c");
Set<Integer> set = CollUtil.newHashSet(1, 2, 3);
Map<String, Object> map = CollUtil.newHashMap();
// 集合判空
boolean empty = CollUtil.isEmpty(list);
boolean notEmpty = CollUtil.isNotEmpty(list);2.集合操作
java
// 集合分割
List<List<String>> partition = CollUtil.partition(list, 2);
// [[a, b], [c]]
// 集合过滤
List<String> filtered = CollUtil.filter(list, str -> str.equals("a"));
// 集合转换
List<Integer> intList = CollUtil.map(list, String::length, true);
// 集合交集、并集、差集
List<String> intersection = CollUtil.intersection(list1, list2);
List<String> union = CollUtil.union(list1, list2);
List<String> disjunction = CollUtil.disjunction(list1, list2);四、对象工具(ObjectUtil)
java
import cn.hutool.core.util.ObjectUtil;
// 对象判空
ObjectUtil.isEmpty(null); // true
ObjectUtil.isEmpty(""); // true
ObjectUtil.isEmpty(new Object()); // false
// 对象比较
boolean equal = ObjectUtil.equal(obj1, obj2);
boolean notEqual = ObjectUtil.notEqual(obj1, obj2);
// 对象转字符串
String str = ObjectUtil.toString(obj);五、类型转换(Convert)
java
import cn.hutool.core.convert.Convert;
// 转换为int
int intVal = Convert.toInt("123");
int intVal = Convert.toInt("123", 0); // 默认值
// 转换为Long
long longVal = Convert.toLong("123456789");
// 转换为String
String str = Convert.toStr(123);
// 转换为Boolean
boolean bool = Convert.toBool("true");
// 转换为BigDecimal
BigDecimal decimal = Convert.toBigDecimal("123.45");六、随机工具(RandomUtil)
java
import cn.hutool.core.util.RandomUtil;
// 随机整数
int randomInt = RandomUtil.randomInt(); // 随机整数
int randomInt = RandomUtil.randomInt(10); // 0-9
int randomInt = RandomUtil.randomInt(1, 10); // 1-9
// 随机长整数
long randomLong = RandomUtil.randomLong();
// 随机字符串
String randomStr = RandomUtil.randomString(6); // 随机字符串
String randomNumbers = RandomUtil.randomNumbers(6); // 随机数字
String randomStringUpper = RandomUtil.randomStringUpper(6); // 大写字母第三部分 加密解密(hutool-crypto)
一、MD5加密
java
import cn.hutool.crypto.digest.DigestUtil;
// MD5加密
String md5Hex = DigestUtil.md5Hex("123456");
// 输出:e10adc3949ba59abbe56e057f20f883e
// 带盐值的MD5
String md5Hex = DigestUtil.md5Hex("123456" + "salt");
// MD5加密文件
String md5Hex = DigestUtil.md5Hex(new File("test.txt"));二、SHA加密
java
// SHA-1加密
String sha1Hex = DigestUtil.sha1Hex("123456");
// SHA-256加密
String sha256Hex = DigestUtil.sha256Hex("123456");
// SHA-512加密
String sha512Hex = DigestUtil.sha512Hex("123456");三、对称加密(AES)
java
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
// AES加密
byte[] key = "0123456789ABCDEF".getBytes();
AES aes = new AES(key);
// 加密
byte[] encrypt = aes.encrypt("123456");
String encryptHex = aes.encryptHex("123456");
// 解密
byte[] decrypt = aes.decrypt(encrypt);
String decryptStr = aes.decryptStr(encryptHex);四、非对称加密(RSA)
java
import cn.hutool.crypto.asymmetric.RSA;
// 生成密钥对
RSA rsa = new RSA();
String privateKey = rsa.getPrivateKeyBase64();
String publicKey = rsa.getPublicKeyBase64();
// 公钥加密
byte[] encrypt = rsa.encrypt("123456", KeyType.PublicKey);
String encryptHex = rsa.encryptHex("123456", KeyType.PublicKey);
// 私钥解密
byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
String decryptStr = rsa.decryptStr(encryptHex, KeyType.PrivateKey);
// 私钥签名
byte[] sign = rsa.sign("123456".getBytes());
// 公钥验签
boolean verify = rsa.verify("123456".getBytes(), sign);第四部分 HTTP客户端(hutool-http)
一、GET请求
java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
// 简单GET请求
String result = HttpRequest.get("https://www.example.com")
.execute()
.body();
// 带参数的GET请求
String result = HttpRequest.get("https://www.example.com")
.form("param1", "value1")
.form("param2", "value2")
.execute()
.body();
// 带Header的GET请求
HttpResponse response = HttpRequest.get("https://www.example.com")
.header(Header.AUTHORIZATION, "Bearer token123")
.execute();
int status = response.getStatus();
String body = response.body();
Map<String, List<String>> headers = response.headers();二、POST请求
java
// POST JSON
String result = HttpRequest.post("https://www.example.com")
.body("{\"key\":\"value\"}")
.execute()
.body();
// POST表单
String result = HttpRequest.post("https://www.example.com")
.form("key1", "value1")
.form("key2", "value2")
.execute()
.body();
// POST文件
HttpResponse response = HttpRequest.post("https://www.example.com/upload")
.form("file", new File("test.txt"))
.execute();三、配置选项
java
HttpResponse response = HttpRequest.get("https://www.example.com")
.timeout(5000) // 超时设置(毫秒)
.header(Header.USER_AGENT, "Hutool Http") // 设置User-Agent
.cookie("session", "abc123") // 设置Cookie
.execute();第五部分 JSON工具(hutool-json)
一、JSON解析
java
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
// 解析JSON字符串
JSONObject jsonObject = JSONUtil.parseObj("{\"name\":\"Tom\",\"age\":18}");
String name = jsonObject.getStr("name");
int age = jsonObject.getInt("age");
// 解析JSON数组
JSONArray jsonArray = JSONUtil.parseArray("[1,2,3]");
int first = jsonArray.getInt(0);二、JSON生成
java
// 对象转JSON
User user = new User("Tom", 18);
String json = JSONUtil.toJsonStr(user);
// Map转JSON
Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", 18);
String json = JSONUtil.toJsonPrettyStr(map);
// JSON转对象
User user = JSONUtil.toBean(jsonStr, User.class);三、XML转JSON
java
// XML转JSON
String xml = "<user><name>Tom</name><age>18</age></user>";
JSONObject json = JSONUtil.parseFromXml(xml);第六部分 常见问题
一、版本选择
推荐版本
- 稳定版:5.8.x(推荐)
- 旧版本:4.x(兼容JDK 7)
- 新版本:6.x(实验性)
二、常见问题
[Q: 如何选择引入方式?]
如果项目中只需要部分功能,建议单独引入对应模块;如果需要大量使用,建议引入hutool-all~
[Q: 工具类冲突怎么办?]
如果项目中已有其他工具类库(如Apache Commons),可能会有方法冲突,建议统一使用一种~