前言
hutool是作者的一个自造词,hu tool,hu指的是他的前公司,谐音:糊涂,意为"万事都作糊涂观,无所谓失,无所谓得",tool就是“工具”的意思
hutool简略大纲
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
convert 类型转换
// int转字符串
int a = 1;
String aStr = Convert.toStr(a);
// 字符串转int
String param = "10";
int paramInt = Convert.toInt(param);
// 重载 第二个参数 defaultValue 可用于在转换失败时返回一个默认值
int paramIntDefault = Convert.toInt(param, 0);
// 转换为指定类型数组
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
// 转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
// 转为Unicode
String unicodeStr = "紫邪情";
String unicode = Convert.strToUnicode(unicodeStr);
// 转换为List
String[] strArr = {"a", "b", "c", "d"};
List<String> strList = Convert.toList(String.class, strArr);
DataUtil 日期时间
此工具定义了一些操作日期的方法: Date、long、Calendar之间的相互转换
// 当前时间
// 返回的其实是 DateTime,它继承自 Date 对象,重写了 toString() 方法,返回 yyyy-MM-dd HH:mm:ss 格式的字符串
Date date = DateUtil.date();
// 字符串转日期
/*
DateUtil.parse()会自动识别一些格式,比如:
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
HH:mm:ss
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss.SSS
而且还可以自动识别带中文的
年月日时分秒
*/
String dateStr = "2021-08-28";
Date date = DateUtil.parse(dateStr);
// 自定义格式化转换
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
// 星座、属相
// 射手座
String zodiac = DateUtil.getZodiac(Month.DECEMBER.getValue(), 10);
// 蛇
String chineseZodiac = DateUtil.getChineseZodiac(1989);
// Calendar转Date
date = DateUtil.date(Calendar.getInstance());
// 时间戳转Date
date = DateUtil.date(System.currentTimeMillis());
// 格式化输出日期
String format = DateUtil.format(date, "yyyy-MM-dd");
// 获得年的部分
int year = DateUtil.year(date);
// 获得月份,从0开始计数
int month = DateUtil.month(date);
// 获取某天的开始、结束时间
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
// 计算偏移后的日期时间
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
// 计算日期时间之间的偏移量
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
IO流相关
流操作工具类 IoUtil
文件读写操作工具类 FileUtil
文件类型判断工具类 FileTypeUtil
BufferedInputStream in = FileUtil.getInputStream("hutool/origin.txt");
BufferedOutputStream out = FileUtil.getOutputStream("hutool/to.txt");
long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
此工具还提供得有IO相关的,如下:
- 文件操作:包括文件目录的新建、删除、复制、移动、改名等
- 文件判断:判断文件或目录是否非空,是否为目录,是否为文件等等
- 绝对路径:针对 ClassPath 中的文件转换为绝对路径文件
- 文件名:主文件名,扩展名的获取
- 读操作:包括 getReader、readXXX 操作
- 写操作:包括 getWriter、writeXXX 操作
StrUtil 字符串工具
此工具和Apache Commons Lang 包中的 StringUtils 差不多
// 判断是否为空字符串
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
// 去除字符串的前后缀
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
// 格式化字符串 这个是比较有意思的一个点
String template = "这只是个占位符:{}";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("strUtil format:{}", str2);
ReflectUtil 反射工具
Hutool 封装的反射工具 ReflectUtil 包括:
- 获取构造方法
- 获取字段
- 获取字段值
- 获取方法
- 执行方法(对象方法和静态方法)
import cn.hutool.core.util.ReflectUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectDemo {
private int id;
public ReflectDemo() {
System.out.println("无参构造");
}
public void print() {
System.out.println("我是紫邪情");
}
public static void main(String[] args) throws IllegalAccessException {
// 构建对象
ReflectDemo reflectDemo = ReflectUtil.newInstance(ReflectDemo.class);
// 获取构造方法
Constructor[] constructors = ReflectUtil.getConstructors(ReflectDemo.class);
for (Constructor constructor : constructors) {
System.out.println(constructor.getName());
}
// 获取字段
Field field = ReflectUtil.getField(ReflectDemo.class, "id");
field.setInt(reflectDemo, 10);
// 获取字段值
System.out.println(ReflectUtil.getFieldValue(reflectDemo, field));
// 获取所有方法
Method[] methods = ReflectUtil.getMethods(ReflectDemo.class);
for (Method m : methods) {
System.out.println(m.getName());
}
// 获取指定方法
Method method = ReflectUtil.getMethod(ReflectDemo.class, "print");
System.out.println(method.getName());
// 执行方法
ReflectUtil.invoke(reflectDemo, "print");
}
}
ZipUtil 压缩工具
Hutool 封装的 ZipUtil 针对 java.util.zip 包做了优化,可以使用一个方法搞定压缩和解压,并且自动处理文件和目录的问题,不再需要用户判断
ZipUtil.zip("hutool", "hutool.zip");
File unzip = ZipUtil.unzip("hutool.zip", "hutoolzip");+
IdcardUtil 身份证验证工具
支持大陆 15 位、18 位身份证,港澳台 10 位身份证
String ID_18 = "321083197812162119";
String ID_15 = "150102880730303";
boolean valid = IdcardUtil.isValidCard(ID_18);
boolean valid15 = IdcardUtil.isValidCard(ID_15);
Console 控制台工具
一些复杂的对象不支持直接打印,比如说数组,需要调用 Arrays.toString
。Hutool 封装的 Console 类借鉴了 JavaScript 中的 console.log()
,使得打印变成了一个非常便捷的方式
public class ConsoleDemo {
public static void main(String[] args) {
// 打印字符串
Console.log("紫邪情,一个脸皮厚的人");
// 打印字符串模板
Console.log("洛阳是{}朝古都",13);
int [] ints = {1,2,3,4};
// 打印数组
Console.log(ints);
}
}
Validator 字段验证器
做 Web 开发的时候,后端通常需要对表单提交过来的数据进行验证。Hutool 封装的 Validator 可以进行很多有效的条件验证,以下的方法名见名知意
Validator.isEmail("紫邪情");
Validator.isMobile("itwanger.com");
ImgUtil 图片工具
Hutool 封装的 ImgUtil 可以对图片进行缩放、裁剪、转为黑白、加水印等操作
缩放图片
ImgUtil.scale(
FileUtil.file("hutool/wangsan.jpg"),
FileUtil.file("hutool/wangsan_small.jpg"),
0.5f
);
裁剪图片
ImgUtil.cut(
FileUtil.file("hutool/wangsan.jpg"),
FileUtil.file("hutool/wangsan_cut.jpg"),
new Rectangle(200, 200, 100, 100)
);
添加水印
ImgUtil.pressText(//
FileUtil.file("hutool/wangsan.jpg"),
FileUtil.file("hutool/wangsan_logo.jpg"),
"沉默王二", Color.WHITE,
new Font("黑体", Font.BOLD, 100),
0,
0,
0.8f
);
setting 配置文件
Java 中广泛应用的配置文件 Properties 存在一个特别大的诟病:不支持中文
于是,Hutool 的 Setting 运用而生。Setting 除了兼容 Properties 文件格式外,还提供了一些特有功能,这些功能包括:
- 各种编码方式支持
- 变量支持
- 分组支持
整个example.setting配置文件
name=紫邪情
age=18
读取和更新配置文件
public class SettingDemo {
private final static String SETTING = "hutool/example.setting";
public static void main(String[] args) {
// 初始化 Setting
Setting setting = new Setting(SETTING);
// 读取
setting.getStr("name", "紫邪情");
// 在配置文件变更时自动加载
setting.autoLoad(true);
// 通过代码方式增加键值对
setting.set("birthday", "2021年08月28日");
setting.store(SETTING);
}
}
SecureUtil 加密解密
加密分为三种:
- 对称加密(symmetric),例如:AES、DES 等
- 非对称加密(asymmetric),例如:RSA、DSA 等
- 摘要加密(digest),例如:MD5、SHA-1、SHA-256、HMAC 等
Hutool 针对这三种情况都做了封装:
- 对称加密 SymmetricCrypto
- 非对称加密 AsymmetricCrypto
- 摘要加密 Digester
快速加密工具类 SecureUtil 有以下这些方法:
1)对称加密
- SecureUtil.aes
- SecureUtil.des
2)非对称加密
- SecureUtil.rsa
- SecureUtil.dsa
3)摘要加密
- SecureUtil.md5
- SecureUtil.sha1
- SecureUtil.hmac
- SecureUtil.hmacMd5
- cureUtil.hmacSha1
// MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:{}", md5Str);
String encry = aes.encryptHex("紫邪情");
System.out.println(encry);
String oo = aes.decryptStr(encry);
System.out.println(oo);
CaptchaUtil 验证码工具
此工具用于生成图形验证码
// 生成验证码图片
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
response.setContentType("image/png");//告诉浏览器输出内容为图片
response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
ClassPathResource ClassPath资源工具
此工具是获取ClassPath下的文件,在Tomcat等容器中,ClassPath一般为:WEB-INFO/classes
// 获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);
NumberUtil 四则运算
此工具是用于各种类型数字的加减乘除操作及判断类型
double n1 = 1.234;
double n2 = 1.234;
double result;
// 对float、double、BigDecimal做加减乘除操作
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
// 保留两位小数
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
// 判断是否为数字、整数、浮点数
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
BeanUtil Bean与Map转换工具
此工具是用于Map与JavaBean对象的互相转换以及对象属性的拷贝
PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
brand.setShowStatus(0);
// Bean转Map
Map<String, Object> map = BeanUtil.beanToMap(brand);
LOGGER.info("beanUtil bean to map:{}", map);
// Map转Bean
PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
// Bean属性拷贝
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);
CollUtil 集合工具
// 数组转换为列表
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
// 数组转字符串时添加连接符号
String joinStr = CollUtil.join(list, ",");
LOGGER.info("collUtil join:{}", joinStr);
// 将以连接符号分隔的字符串再转换为列表
List<String> splitList = StrUtil.split(joinStr, ',');
LOGGER.info("collUtil split:{}", splitList);
// 创建新的Map、Set、List
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
// 判断列表是否为空
CollUtil.isEmpty(list);
MapUtil Map集合工具
此工具可用于创建Map和判断Map是否为null
// 将多个键值对加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
});
// 判断Map是否为空
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
AnnotationUtil 注解工具
此工具可用于获取注解和注解中指定的值
// 获取指定类、方法、字段、构造器上的注解列表
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
// 获取指定类型注解
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
// 获取指定类型注解的值
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);