Hutool 基本介绍和使用说明

Hutool 是一个开源的 Java 工具包,旨在简化 Java 开发中的常见操作,提供大量高内聚、低耦合的工具类,覆盖日常开发中频繁使用的功能,如字符串处理、集合操作、IO、日期时间、加密、JSON、HTTP、文件压缩等。它不依赖任何第三方框架,体积轻量(核心模块仅约 1MB),易于集成,特别适合中小型项目或需要快速开发的场景。


✅ Hutool 的主要作用

  • 简化开发:封装常用操作,避免重复造轮子。
  • 提升可读性:方法命名清晰,链式调用友好。
  • 减少依赖:无第三方框架依赖(核心模块)。
  • 兼容性强:支持 Java 8+,适配主流 JDK 版本。
  • 文档丰富:官方文档详尽,示例丰富。

📦 Hutool 主要模块及作用(按功能分类)

模块名称作用说明
hutool-core核心模块,包含最常用的工具类:字符串、集合、日期、IO、反射、加密、系统信息等。
hutool-crypto加密解密工具,支持 AES、RSA、SHA、MD5、Base64、哈希等。
hutool-db简化 JDBC 操作,提供 DbSqlRunner 等类,无需写原生 SQL 模板。
hutool-http封装 HTTP 请求(GET/POST/PUT/DELETE),支持上传、Cookie、Header、代理等。
hutool-jsonJSON 处理工具,基于 org.json,支持 JSONObjectJSONArray 的便捷操作。
hutool-log日志门面封装,支持 Log4j、Logback、SLF4J 等,统一接口。
hutool-cache缓存工具,提供 Cache 接口及 LRU、TTL 等实现。
hutool-extra扩展模块,包含邮件、模板引擎(Velocity)、二维码、PDF、Excel 等高级功能。
hutool-aop简单 AOP 切面支持,用于方法拦截、日志记录等。
hutool-system系统信息获取,如 CPU、内存、磁盘、进程等。
hutool-poi封装 Apache POI,简化 Excel 读写操作(.xlsx / .xls)。
hutool-script脚本引擎支持,如 JavaScript(Nashorn)、Groovy 等。
hutool-bloomfilter布隆过滤器实现,用于大数据量去重场景。
hutool-weixin微信相关工具(公众号、小程序 API 封装)。
hutool-socketSocket 通信工具,简化 TCP/UDP 编程。
hutool-jwtJWT(JSON Web Token)生成与解析工具模块。

开发建议:一般项目只需引入 hutool-corehutool-http 即可满足 80% 需求。


🔧 Hutool 常用工具类及详细使用示例(含中文注释)

1. StrUtil — 字符串工具类
import cn.hutool.core.util.StrUtil;

public class StrUtilExample {
    public static void main(String[] args) {
        // 判断字符串是否为空(null、""、空白字符均返回 true)
        boolean isEmpty = StrUtil.isEmpty("   "); // true
        System.out.println("字符串是否为空: " + isEmpty);

        // 判断字符串是否为非空(与 isEmpty 相反)
        boolean isNotEmpty = StrUtil.isNotEmpty("Hello"); // true
        System.out.println("字符串是否非空: " + isNotEmpty);

        // 去除首尾空格并判断是否为空
        boolean isBlank = StrUtil.isBlank(" \t\n "); // true
        System.out.println("字符串是否为空白: " + isBlank);

        // 截取字符串(从第2位开始,截取3个字符)
        String sub = StrUtil.sub("HelloWorld", 2, 5); // "llo"
        System.out.println("截取子串: " + sub);

        // 格式化字符串(类似 String.format)
        String formatted = StrUtil.format("姓名:{},年龄:{}", "张三", 25);
        System.out.println("格式化字符串: " + formatted); // 姓名:张三,年龄:25

        // 将字符串转为驼峰命名(下划线转驼峰)
        String camel = StrUtil.toCamelCase("user_name"); // "userName"
        System.out.println("下划线转驼峰: " + camel);

        // 驼峰转下划线
        String underscore = StrUtil.toUnderlineCase("userName"); // "user_name"
        System.out.println("驼峰转下划线: " + underscore);

        // 拼接多个字符串,用逗号分隔
        String join = StrUtil.join(",", "A", "B", "C"); // "A,B,C"
        System.out.println("拼接字符串: " + join);
    }
}

2. CollectionUtil — 集合工具类
import cn.hutool.core.collection.CollUtil;
import java.util.*;

public class CollectionUtilExample {
    public static void main(String[] args) {
        // 创建一个非空列表(避免 null)
        List<String> list = CollUtil.newArrayList("苹果", "香蕉", "橙子");
        System.out.println("创建列表: " + list);

        // 判断集合是否为空
        boolean isEmpty = CollUtil.isEmpty(list); // false
        System.out.println("集合是否为空: " + isEmpty);

        // 判断集合是否包含某个元素
        boolean contains = CollUtil.contains(list, "香蕉"); // true
        System.out.println("是否包含香蕉: " + contains);

        // 将数组转为集合
        String[] arr = {"A", "B", "C"};
        List<String> fromArray = CollUtil.newArrayList(arr);
        System.out.println("数组转集合: " + fromArray);

        // 过滤集合(保留长度大于 2 的字符串)
        List<String> filtered = CollUtil.filter(list, s -> s.length() > 2);
        System.out.println("过滤后: " + filtered); // [苹果, 香蕉, 橙子]

        // 转为 Map(key-value 对)
        Map<String, String> map = CollUtil.map("name", "张三", "age", "25");
        System.out.println("转为 Map: " + map); // {name=张三, age=25}

        // 合并两个集合
        List<String> list2 = CollUtil.newArrayList("葡萄", "梨子");
        List<String> merged = CollUtil.addAll(list, list2);
        System.out.println("合并后: " + merged);
    }
}

3. DateUtil — 日期时间工具类
import cn.hutool.core.date.DateUtil;
import java.util.Date;

public class DateUtilExample {
    public static void main(String[] args) {
        // 获取当前时间
        Date now = new Date();
        System.out.println("当前时间: " + now);

        // 格式化日期为字符串(yyyy-MM-dd HH:mm:ss)
        String formatted = DateUtil.format(now, "yyyy-MM-dd HH:mm:ss");
        System.out.println("格式化日期: " + formatted);

        // 解析字符串为 Date 对象
        Date parsed = DateUtil.parse("2025-01-01 12:30:00", "yyyy-MM-dd HH:mm:ss");
        System.out.println("解析日期: " + parsed);

        // 获取当前时间戳(毫秒)
        long timestamp = DateUtil.current();
        System.out.println("当前时间戳: " + timestamp);

        // 计算两个日期相差天数
        Date start = DateUtil.parse("2025-01-01");
        Date end = DateUtil.parse("2025-01-10");
        long days = DateUtil.betweenDay(start, end, false); // false 表示不包含起始日
        System.out.println("相差天数: " + days); // 9

        // 获取当前时间的前7天
        Date weekAgo = DateUtil.offsetDay(new Date(), -7);
        System.out.println("一周前: " + DateUtil.format(weekAgo, "yyyy-MM-dd"));

        // 判断是否为今天
        boolean isToday = DateUtil.isToday(new Date());
        System.out.println("是否为今天: " + isToday);
    }
}

4. FileUtil — 文件与 IO 工具类
import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.util.List;

public class FileUtilExample {
    public static void main(String[] args) {
        // 创建临时文件
        File tempFile = FileUtil.tempFile();
        System.out.println("临时文件路径: " + tempFile.getAbsolutePath());

        // 判断文件是否存在
        boolean exists = FileUtil.exist("D:/test.txt");
        System.out.println("文件是否存在: " + exists);

        // 读取文件内容为字符串(UTF-8)
        String content = FileUtil.readString("D:/test.txt", "UTF-8");
        System.out.println("文件内容: " + content);

        // 写入内容到文件(自动创建目录)
        FileUtil.writeUtf8String("Hello Hutool!", "D:/output/hello.txt");

        // 获取文件扩展名
        String ext = FileUtil.extName("document.pdf"); // "pdf"
        System.out.println("文件扩展名: " + ext);

        // 获取文件大小(字节)
        long size = FileUtil.size(new File("D:/test.txt"));
        System.out.println("文件大小: " + size + " 字节");

        // 递归删除目录
        FileUtil.del("D:/tempDir"); // 删除整个目录及其内容

        // 获取目录下所有文件(递归)
        List<File> files = FileUtil.loopFiles("D:/data");
        System.out.println("目录下文件数: " + files.size());
    }
}

5. JsonUtil — JSON 工具类
import cn.hutool.json.JSONUtil;
import java.util.HashMap;
import java.util.Map;

public class JsonUtilExample {
    public static void main(String[] args) {
        // 创建 Java 对象
        Map<String, Object> user = new HashMap<>();
        user.put("name", "李四");
        user.put("age", 30);
        user.put("married", false);

        // 将 Java 对象转为 JSON 字符串
        String jsonStr = JSONUtil.toJsonStr(user);
        System.out.println("Java 对象转 JSON: " + jsonStr);
        // 输出: {"name":"李四","age":30,"married":false}

        // 将 JSON 字符串转为 Map
        Map<String, Object> parsed = JSONUtil.parseObj(jsonStr);
        System.out.println("JSON 转回 Map: " + parsed.get("name")); // 李四

        // 转为 JavaBean(需有无参构造)
        UserBean userBean = JSONUtil.toBean(jsonStr, UserBean.class);
        System.out.println("转为 JavaBean: " + userBean.getName());

        // 格式化 JSON(带缩进)
        String prettyJson = JSONUtil.toJsonPrettyStr(user);
        System.out.println("格式化 JSON:\n" + prettyJson);
    }

    // 用于转换的 JavaBean 类
    static class UserBean {
        private String name;
        private Integer age;
        private Boolean married;

        // getter/setter 必须有
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public Integer getAge() { return age; }
        public void setAge(Integer age) { this.age = age; }
        public Boolean getMarried() { return married; }
        public void setMarried(Boolean married) { this.married = married; }
    }
}

6. HttpUtil — HTTP 请求工具类(GET/POST)
import cn.hutool.http.Method;
import cn.hutool.http.Request;
import cn.hutool.http.Response;

public class HttpUtilExample {
    public static void main(String[] args) {
        // 发起 GET 请求
        String response = cn.hutool.http.HttpUtil.get("https://httpbin.org/get");
        System.out.println("GET 请求响应:\n" + response);

        // 发起 POST 请求(带参数)
        String postResult = cn.hutool.http.HttpUtil.post("https://httpbin.org/post",
                "name=王五&age=28");
        System.out.println("POST 请求响应:\n" + postResult);

        // 使用 Request 对象更灵活控制
        Request request = cn.hutool.http.Request.create(Method.POST, "https://httpbin.org/post")
                .addHeader("Content-Type", "application/json")
                .addHeader("User-Agent", "Hutool-Client")
                .body("{\"name\":\"赵六\",\"city\":\"北京\"}"); // JSON 格式请求体

        Response response2 = request.execute();
        System.out.println("自定义 Header POST 响应状态码: " + response2.getStatus());
        System.out.println("响应内容: " + response2.body());
    }
}

7. ZipUtil — 压缩与解压工具类(重点)
import cn.hutool.archive.zip.ZipUtil;
import java.io.File;
import java.util.List;

public class ZipUtilExample {
    public static void main(String[] args) {
        // 1. 压缩文件夹为 ZIP
        // 将 "D:/source" 目录下的所有文件压缩成 "D:/backup.zip"
        File sourceDir = new File("D:/source");
        File zipFile = new File("D:/backup.zip");

        // 创建压缩文件(如果目录不存在会自动创建)
        ZipUtil.zip(zipFile, sourceDir);
        System.out.println("✅ 已将目录压缩为: " + zipFile.getAbsolutePath());

        // 2. 压缩多个文件
        File file1 = new File("D:/source/file1.txt");
        File file2 = new File("D:/source/file2.txt");
        File multiZip = new File("D:/multi_files.zip");
        ZipUtil.zip(multiZip, file1, file2);
        System.out.println("✅ 已将多个文件压缩为: " + multiZip.getAbsolutePath());

        // 3. 解压 ZIP 文件到指定目录
        File destDir = new File("D:/extracted");
        ZipUtil.unzip(zipFile, destDir); // 解压到 D:/extracted
        System.out.println("✅ 已将 " + zipFile.getName() + " 解压到: " + destDir.getAbsolutePath());

        // 4. 查看 ZIP 文件中包含的文件列表
        List<File> entries = ZipUtil.list(zipFile);
        System.out.println("ZIP 文件内包含的文件:");
        entries.forEach(entry -> System.out.println("  - " + entry.getName()));

        // 5. 压缩时指定编码(解决中文文件名乱码问题)
        // Hutool 默认使用 UTF-8,但在某些系统(如 Windows)中可能需指定
        ZipUtil.zip(zipFile, sourceDir, "GBK"); // 指定编码为 GBK,避免乱码
        System.out.println("✅ 已使用 GBK 编码重新压缩(适用于中文路径)");
    }
}

⚠️ ZipUtil 使用注意事项

  • 压缩中文文件名时,若目标系统为 Windows,建议显式指定编码为 "GBK",避免乱码。
  • 解压时默认使用 UTF-8,若压缩包是 GBK 编码,需在 unzip(zipFile, destDir, "GBK") 中指定。
  • 压缩和解压操作会覆盖同名文件,请确保目标路径安全。

✅ 推荐使用方式(Maven 依赖)

<!-- 核心模块(必选) -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-core</artifactId>
    <version>5.8.22</version>
</dependency>

<!-- HTTP 请求(推荐) -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.8.22</version>
</dependency>

<!-- JSON 处理(推荐) -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-json</artifactId>
    <version>5.8.22</version>
</dependency>

<!-- 文件压缩(ZipUtil)已包含在 hutool-core 中 -->

版本建议:使用最新稳定版(当前推荐 5.8.x),避免使用过旧版本。


📌 总结:Hutool 的优势

优势说明
轻量无依赖核心模块无第三方依赖,适合嵌入式项目
API 简洁方法命名直观,链式调用流畅
覆盖全面几乎涵盖 Java 开发 90% 常用工具
社区活跃GitHub Star 超 40k,文档完善
企业级应用国内大量银行、保险、政务系统采用

💡 开发建议

  • 优先使用 StrUtilCollectionUtilDateUtilFileUtilJsonUtilHttpUtilZipUtil
  • 避免过度依赖 hutool-extra 中的复杂模块(如 POI、PDF),除非必要。
  • 在团队中统一 Hutool 版本,避免因版本差异导致兼容问题。
  • 对于高并发场景,注意 ZipUtil 的资源释放(建议使用 try-with-resources 或手动关闭流)。

如需进一步学习,可访问官方文档:https://hutool.cn/
Hutool 是 Java 开发者的“瑞士军刀”,合理使用可显著提升开发效率!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值