前言
Hutool 是一款功能全面的 Java 工具类库,它提供了一系列高效、便捷的方法,简化了日常开发中的常见操作。本文将详细介绍其中几个常用工具类,并给出详尽的使用示例。
1. 数据类型转换 - Convert
Convert 类提供了各种数据类型的转换方法,包括基本类型、包装类型和对象之间的转换:
import cn.hutool.core.convert.Convert;
// 基本类型转换
int number = Convert.toInt("123"); // 将字符串转为整型
String str = Convert.toStr(123); // 将整型转为字符串
// 对象类型转换
List<String> list = Arrays.asList("a", "b");
Set<String> set = Convert.convert(Set.class, list); // 将列表转为集合
// 自定义转换器
Converter<String, User> converter = new Converter<String, User>() {
@Override
public User convert(String source) {
return new User(source);
}
};
User user = Convert.convert(converter, "John Doe");
2. 时间日期处理 - DateUtil
DateUtil 提供了丰富的日期时间操作:
import cn.hutool.core.date.DateUtil;
// 获取当前日期时间
Date now = DateUtil.date();
// 格式化日期
String formatDateTime = DateUtil.format(now, "yyyy-MM-dd HH:mm:ss");
// 解析日期
Date date = DateUtil.parse("2023-03-24 15:30:45", "yyyy-MM-dd HH:mm:ss");
// 计算两个日期之间的差值
long daysBetween = DateUtil.between(date, new Date(), DateUnit.DAY);
3. 字符串处理 - StrUtil
StrUtil 提供了大量的字符串操作工具方法:
import cn.hutool.core.util.StrUtil;
// 判断字符串是否为空或空白
boolean isEmpty = StrUtil.isBlank(" "); // true if blank space
// 连接字符串
String joinResult = StrUtil.join(",", Arrays.asList("Hello", "World")); // "Hello,World"
// 截取字符串
String substring = StrUtil.subPre("Hello World", 5); // "Hello"
// 替换字符串
String replaceResult = StrUtil.replace("Hello {name}", "{name}", "John"); // "Hello John"
4. 文件操作 - FileUtil
FileUtil 提供了方便的文件与目录操作:
import cn.hutool.core.io.FileUtil;
// 创建目录
FileUtil.mkdir("D:/temp");
// 检查文件是否存在
boolean exists = FileUtil.exist("D:/temp/test.txt");
// 读取文件内容
String content = FileUtil.readString("D:/temp/test.txt", StandardCharsets.UTF_8);
// 写入文件
FileUtil.writeString("Hello, Hutool!", "D:/temp/output.txt", StandardCharsets.UTF_8);
通过上述介绍,我们了解了 Hutool 中 Convert、DateUtil、StrUtil 和 FileUtil 等常用工具类的功能及用法。实际上,Hutool 还包含许多其他强大的工具类,如网络请求 HttpUtil、加密解密 Crypto、反射工具 ReflectUtil 等,它们都致力于让 Java 开发变得更加简单高效。在实际项目中,灵活运用这些工具类可以极大地提高开发效率并减少代码量。