Hutool 工具库实战
本文介绍 Hutool 工具库在 Java 项目中的常见用法,覆盖字符串、集合、日期、文件、随机数、Bean、JSON、HTTP 和加密摘要等高频场景。文章重点说明 Hutool 如何减少字符串判空、集合处理、日期格式化、文件读写、Bean 拷贝等重复代码,以及在真实业务中使用工具类时需要注意的边界。
第一章 Hutool 学习思路
1.1 Hutool 是什么
Hutool 是一个常用 Java 工具库,它对 JDK 中分散、繁琐的 API 做了封装,覆盖字符串、集合、日期、文件、随机数、Bean、JSON、HTTP、加密等常见开发场景。
简单理解:Hutool 是 Java 日常开发工具箱。
| 能力 | 常用工具类 |
|---|---|
| 字符串处理 | StrUtil |
| 集合处理 | CollUtil |
| 日期时间 | DateUtil |
| 文件读写 | FileUtil |
| 随机数据 | RandomUtil |
| Bean 转换 | BeanUtil |
| JSON 转换 | JSONUtil |
| HTTP 请求 | HttpUtil |
| 加密摘要 | SecureUtil |
1.2 先理解原生写法,再使用工具库
工具库最怕“只会调用,不懂原理”。比如:
StrUtil.isBlank(str)本质上还是判断字符串是否为null、空串或全空白字符。FileUtil.readUtf8Lines(path)本质上还是打开文件、按 UTF-8 解码、逐行读取、关闭流。BeanUtil.copyProperties(source, Target.class)本质上还是根据属性名和类型做对象属性复制。
推荐路线是:
- 先用 JDK 原生 API 写一遍,知道底层做了什么。
- 再用 Hutool 简化重复代码。
- 最后在团队项目里统一版本和使用规范。
1.3 引入 Hutool
学习阶段可以直接引入 hutool-all,它包含 Hutool 的常用模块:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.26</version>
</dependency>
真实项目中如果很关注依赖体积,也可以按模块引入,例如 hutool-core、hutool-json、hutool-http。初学阶段先使用 hutool-all 更容易把知识串起来。
第二章 字符串工具 StrUtil
2.1 字符串判空
字符串判空是项目里最常见的判断之一。JDK 写法通常比较啰嗦:
public class JdkStringDemo {
public static void main(String[] args) {
String name = " ";
boolean blank = name == null || name.trim().isEmpty();
System.out.println(blank);
}
}
Hutool 写法更直接:
import cn.hutool.core.util.StrUtil;
public class HutoolStringDemo {
public static void main(String[] args) {
String username = " ";
System.out.println(StrUtil.isBlank(username));
System.out.println(StrUtil.isNotBlank("admin"));
}
}
常用方法:
| 方法 | 作用 |
|---|---|
isBlank | 判断是否为 null、空串或全空白 |
isNotBlank | 判断是否不是空白字符串 |
isEmpty | 判断是否为 null 或空串 |
isNotEmpty | 判断不是 null 且不是空串 |
isBlank 会把 " " 这种全空格字符串当成空白,业务表单校验中更常用。
2.2 默认值处理
import cn.hutool.core.util.StrUtil;
public class DefaultValueDemo {
public static void main(String[] args) {
String nickname = "";
String result = StrUtil.emptyToDefault(nickname, "匿名用户");
System.out.println(result);
}
}
常见场景:
- 用户昵称为空时显示默认昵称。
- 查询参数为空时使用默认条件。
- 配置项为空时使用默认配置。
2.3 字符串格式化
import cn.hutool.core.util.StrUtil;
public class StringFormatDemo {
public static void main(String[] args) {
String message = StrUtil.format("用户:{},积分:{}", "张三", 100);
System.out.println(message);
}
}
StrUtil.format 使用 {} 作为占位符,比字符串拼接更清晰。
2.4 字符串截取
import cn.hutool.core.util.StrUtil;
public class StringSubDemo {
public static void main(String[] args) {
String email = "admin@example.com";
System.out.println(StrUtil.subBefore(email, "@", false));
System.out.println(StrUtil.subAfter(email, "@", false));
}
}
常用方法:
| 方法 | 作用 |
|---|---|
subBefore | 截取指定分隔符前的内容 |
subAfter | 截取指定分隔符后的内容 |
subBetween | 截取两个标记中间的内容 |
第三章 集合工具 CollUtil
3.1 集合判空
集合最常见的问题是空指针和空集合判断。
import cn.hutool.core.collection.CollUtil;
import java.util.List;
public class HutoolCollectionDemo {
public static void main(String[] args) {
List<String> names = CollUtil.newArrayList("Java", "MySQL", "Spring");
System.out.println(CollUtil.isEmpty(names));
System.out.println(CollUtil.isNotEmpty(names));
}
}
常用方法:
| 方法 | 作用 |
|---|---|
isEmpty | 判断集合是否为 null 或空 |
isNotEmpty | 判断集合不为空 |
newArrayList | 快速创建 ArrayList |
newHashSet | 快速创建 HashSet |
3.2 集合拼接
import cn.hutool.core.collection.CollUtil;
import java.util.List;
public class CollectionJoinDemo {
public static void main(String[] args) {
List<String> courses = CollUtil.newArrayList("Java", "Spring Boot", "MyBatis");
String text = CollUtil.join(courses, " / ");
System.out.println(text);
}
}
集合拼接常用于:
- 页面展示标签。
- 日志输出。
- 把多个编号拼成一段字符串。
3.3 集合包含判断
import cn.hutool.core.collection.CollUtil;
import java.util.List;
public class CollectionContainsDemo {
public static void main(String[] args) {
List<String> roles = CollUtil.newArrayList("admin", "manager");
if (CollUtil.contains(roles, "admin")) {
System.out.println("拥有管理员权限");
}
}
}
第四章 日期工具 DateUtil
4.1 日期格式化
如果项目还在使用 Date,Hutool 的 DateUtil 可以让格式化、解析、加减时间更轻松。
import cn.hutool.core.date.DateUtil;
import java.util.Date;
public class DateFormatDemo {
public static void main(String[] args) {
Date now = new Date();
System.out.println(DateUtil.formatDate(now));
System.out.println(DateUtil.formatDateTime(now));
System.out.println(DateUtil.format(now, "yyyy年MM月dd日 HH:mm"));
}
}
常用方法:
| 方法 | 作用 |
|---|---|
formatDate | 格式化成 yyyy-MM-dd |
formatDateTime | 格式化成 yyyy-MM-dd HH:mm:ss |
format | 按指定模板格式化 |
4.2 日期解析
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
public class DateParseDemo {
public static void main(String[] args) {
DateTime birthday = DateUtil.parse("2000-01-01");
System.out.println(birthday);
}
}
4.3 日期加减和时间差
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.util.Date;
public class DateOffsetDemo {
public static void main(String[] args) {
Date now = new Date();
DateTime tomorrow = DateUtil.offsetDay(now, 1);
long days = DateUtil.betweenDay(now, tomorrow, false);
System.out.println(DateUtil.formatDate(tomorrow));
System.out.println(days);
}
}
第五章 文件工具 FileUtil
5.1 文件写入和读取
文件读写在原生 IO 中需要处理流、编码和异常。Hutool 把常见操作做成了简单方法。
import cn.hutool.core.io.FileUtil;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class HutoolFileDemo {
public static void main(String[] args) {
FileUtil.writeString("第一行\n第二行", "demo.txt", StandardCharsets.UTF_8);
List<String> lines = FileUtil.readLines("demo.txt", StandardCharsets.UTF_8);
lines.forEach(System.out::println);
}
}
常用方法:
| 方法 | 作用 |
|---|---|
readUtf8String | 按 UTF-8 读取整个文件 |
readUtf8Lines | 按 UTF-8 读取所有行 |
writeUtf8String | 按 UTF-8 写入字符串 |
appendUtf8String | 按 UTF-8 追加字符串 |
5.2 文件复制和删除
import cn.hutool.core.io.FileUtil;
public class FileCopyDemo {
public static void main(String[] args) {
FileUtil.copy("demo.txt", "demo-copy.txt", true);
FileUtil.del("temp.txt");
}
}
删除文件或目录时要谨慎,尤其不要把用户输入直接拼成删除路径。
5.3 文件路径和文件名
import cn.hutool.core.io.FileUtil;
public class FileNameDemo {
public static void main(String[] args) {
String path = "D:/upload/avatar.png";
System.out.println(FileUtil.getName(path));
System.out.println(FileUtil.extName(path));
System.out.println(FileUtil.mainName(path));
}
}
第六章 随机工具 RandomUtil
6.1 常用随机数据
import cn.hutool.core.util.RandomUtil;
public class HutoolRandomDemo {
public static void main(String[] args) {
System.out.println(RandomUtil.randomInt(1, 100));
System.out.println(RandomUtil.randomString(6));
System.out.println(RandomUtil.randomNumbers(6));
}
}
常见用途:
- 生成验证码。
- 生成测试数据。
- 从指定范围中随机取数。
- 生成临时标识。
6.2 验证码示例
import cn.hutool.core.util.RandomUtil;
public class VerifyCodeDemo {
/**
* 生成指定长度的数字验证码。
*
* @param length 验证码长度
* @return 数字验证码
*/
public static String createNumberCode(int length) {
return RandomUtil.randomNumbers(length);
}
public static void main(String[] args) {
System.out.println(createNumberCode(6));
}
}
验证码有有效期和次数限制时,随机数只是第一步,还要配合缓存和校验逻辑。
第七章 Bean 工具 BeanUtil
7.1 Bean 拷贝的使用场景
在 Web 项目中,经常需要在实体类、DTO、VO 之间复制属性。
import cn.hutool.core.bean.BeanUtil;
public class HutoolBeanDemo {
public static void main(String[] args) {
UserEntity entity = new UserEntity();
entity.setId(1L);
entity.setUsername("zhangsan");
entity.setPassword("123456");
UserVO vo = BeanUtil.copyProperties(entity, UserVO.class);
System.out.println(vo.getUsername());
}
}
public class UserEntity {
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class UserVO {
private Long id;
private String username;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
7.2 Bean 拷贝的注意事项
Bean 拷贝适合字段名一致、结构简单的对象。如果字段需要计算、脱敏、枚举转换,最好手动写转换方法,让业务逻辑更清楚。
比如用户密码、手机号脱敏、订单状态文案转换,都不建议完全依赖 Bean 拷贝自动完成。
第八章 JSON 工具 JSONUtil
8.1 对象转 JSON
JSON 是前后端交互和接口调用中最常见的数据格式之一。
import cn.hutool.json.JSONUtil;
public class ToJsonDemo {
public static void main(String[] args) {
UserVO user = new UserVO();
user.setId(1L);
user.setUsername("lisi");
String json = JSONUtil.toJsonStr(user);
System.out.println(json);
}
}
8.2 JSON 转对象
import cn.hutool.json.JSONUtil;
public class FromJsonDemo {
public static void main(String[] args) {
String json = "{\"id\":1,\"username\":\"lisi\"}";
UserVO user = JSONUtil.toBean(json, UserVO.class);
System.out.println(user.getUsername());
}
}
常用方法:
| 方法 | 作用 |
|---|---|
toJsonStr | Java 对象转 JSON 字符串 |
toBean | JSON 字符串转 Java 对象 |
parseObj | 转成 JSONObject |
parseArray | 转成 JSONArray |
第九章 HTTP 工具 HttpUtil
9.1 发送 GET 请求
在学习接口调用时,HttpUtil 可以快速发送 GET 和 POST 请求。
import cn.hutool.http.HttpUtil;
public class HttpGetDemo {
public static void main(String[] args) {
String result = HttpUtil.get("https://example.com");
System.out.println(result);
}
}
9.2 发送 POST 请求
import cn.hutool.http.HttpUtil;
import java.util.HashMap;
import java.util.Map;
public class HttpPostDemo {
public static void main(String[] args) {
Map<String, Object> params = new HashMap<>();
params.put("username", "admin");
params.put("password", "123456");
String result = HttpUtil.post("https://example.com/login", params);
System.out.println(result);
}
}
学习阶段用它很方便。生产项目如果接口调用复杂,比如需要连接池、重试、熔断、统一鉴权,通常会使用更完整的 HTTP 客户端方案,并在项目中统一封装。
第十章 加密摘要 SecureUtil
10.1 常用摘要算法
登录密码不能明文保存,文件校验也经常需要摘要算法。
import cn.hutool.crypto.SecureUtil;
public class HutoolSecureDemo {
public static void main(String[] args) {
String password = "123456";
System.out.println(SecureUtil.md5(password));
System.out.println(SecureUtil.sha256(password));
}
}
10.2 使用注意
MD5、SHA-256 更适合做摘要或校验。真实用户密码存储还需要加盐和更合适的密码哈希方案,不能简单地只做一次 MD5。
常见建议:
- 文件校验可以使用摘要。
- 普通数据签名要配合密钥和签名规则。
- 用户密码不要明文保存。
- 用户密码不要只做一次简单 MD5。
第十一章 Hutool 使用建议
11.1 什么时候适合使用 Hutool
适合使用:
- 字符串、集合、日期、文件等通用操作。
- 快速写 demo 或学习案例。
- 简化重复且没有复杂业务含义的代码。
- 项目团队已经统一 Hutool 版本和使用规范。
不适合滥用:
- 复杂业务规则。
- 安全敏感逻辑。
- 需要严格控制性能和资源的底层组件。
- 团队没有统一依赖版本的项目。
11.2 团队使用规范
| 建议 | 说明 |
|---|---|
| 不要替代基础学习 | 先理解 JDK 原生 API,再用 Hutool 提效 |
| 统一版本 | 团队项目中不要多人随意升级版本 |
| 注意边界 | 工具方法很方便,但复杂业务逻辑仍要自己写清楚 |
| 注意安全 | 加密、HTTP、文件删除等能力要谨慎使用 |
| 避免滥用 Bean 拷贝 | 字段含义不同或需要业务转换时,手动转换更可靠 |
总结
Hutool 是 Java 项目中很常见的效率工具,它提供字符串、集合、日期、文件、随机数、Bean、JSON、HTTP、加密摘要等常用工具能力。
正确使用 Hutool 的关键不是“看到工具就用”,而是先理解 JDK 原生 API,再用工具库减少重复劳动。这样你既能写得快,也知道代码真正做了什么。