简介
中文官网:https://plus.hutool.cn/docs/
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
Hutool的目标是使用一个工具方法代替一段复杂代码,从而最大限度的避免“复制粘贴”代码的问题,彻底改变我们写代码的方式。
包含组件
| 模块 | 介绍 |
|---|---|
| hutool-aop | JDK动态代理封装,提供非IOC下的切面支持 |
| hutool-bloomFilter | 布隆过滤,提供一些Hash算法的布隆过滤 |
| hutool-cache | 简单缓存实现 |
| hutool-core | 核心,包括Bean操作、日期、各种Util等 |
| hutool-cron | 定时任务模块,提供类Crontab表达式的定时任务 |
| hutool-crypto | 加密解密模块,提供对称、非对称和摘要算法封装 |
| hutool-db | JDBC封装后的数据操作,基于ActiveRecord思想 |
| hutool-dfa | 基于DFA模型的多关键字查找 |
| hutool-extra | 扩展模块,对第三方封装(模板引擎、邮件、Servlet、二维码、Emoji、FTP、分词等) |
| hutool-http | 基于HttpUrlConnection的Http客户端封装 |
| hutool-log | 自动识别日志实现的日志门面 |
| hutool-script | 脚本执行封装,例如Javascript |
| hutool-setting | 功能更强大的Setting配置文件和Properties封装 |
| hutool-system | 系统参数调用封装(JVM信息等) |
| hutool-json | JSON实现 |
| hutool-captcha | 图片验证码实现 |
| hutool-poi | 针对POI中Excel和Word的封装 |
| hutool-socket | 基于Java的NIO和AIO的Socket封装 |
| hutool-jwt | JSON Web Token (JWT)封装实现 |
导入
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M4</version>
</dependency>
StrUtil类,对字符串进行处理的工具类。
hasBlank、hasEmpty方法都是用来判断字符串是否为空的
@Test
//判断字符串是否为空
public void hasBlankOrhasEmptyTest(){
String str1 = " ";
String str2 = "";
System.out.println(StrUtil.hasBlank(str1));
System.out.println(StrUtil.hasBlank(str2));
System.out.println(StrUtil.hasEmpty(str1));
System.out.println(StrUtil.hasEmpty(str2));
}
结果
true
true
false
true
hasEmpty方法只能判断为null和空字符串(“”),而hasBlank方法还会将不可见字符也视为空。
removePrefix、removeSuffix分别用于去除字符串的指定前缀和后缀。
//判断是否为空字符串
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);
SecureUtil(加密解密工具)
主要是在登录的时候还有修改密码的时候用到的,因为数据库里面的密码是 md5 加密处理的,所以登录的时候需要先加密之后再到数据库进行查询,使用 Hutool 的话,只需要调用 SecureUtil 中的 md5 方法就可以了。
user = userService.userLoginByName(username,SecureUtil.md5(password));
Convert
类型转换工具类,用于各种类型数据的转换。
//转换为字符串
int a = 1;
String aStr = Convert.toStr(a);
//转换为指定类型数组
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
//转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
//转换为列表
String[] strArr = {"a", "b", "c", "d"};
List<String> strList = Convert.toList(String.class, strArr)
DateUtil
日期时间工具类,定义了一些常用的日期时间操作方法。
//Date、long、Calendar之间的相互转换
//当前时间
Date date = DateUtil.date();
//Calendar转Date
date = DateUtil.date(Calendar.getInstance());
//时间戳转Date
date = DateUtil.date(System.currentTimeMillis());
//自动识别格式转换
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
//自定义格式化转换
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//格式化输出日期
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);
ClassPathResource
获取classPath下的文件,在Tomcat等容器下,classPath一般是WEB-INF/classes。
//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);
ReflectUtil
Java反射工具类,可用于反射获取类的方法及创建对象。
//获取某个类的所有方法
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
//获取某个类的指定方法
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
//使用反射来创建对象
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
//反射执行对象的方法
ReflectUtil.invoke(pmsBrand, "setId", 1);
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
JavaBean的工具类,可用于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);
//join:数组转字符串时添加连接符号
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是否为空。
//将多个键值对加入到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);
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();
}
等等因为hutool里面的东西太多了就做一个表格以供查看吧
| 工具类列表 | |
|---|---|
| Convert | 类型转换工具类 |
| ConverterRegistry | 自定义类型转换 |
| – | – |
| 日期时间 | |
| 日期时间工具 | DateUtil |
| 日期时间对象 | DateTime |
| 农历日期 | ChineseDate |
| LocalDateTime工具 | |
| LocalDateTimeUtil | |
| – | – |
| IO流相关 | |
| IO工具类 | IoUtil |
| 文件工具类 | FileUtil |
| 文件类型判断 | FileTypeUtil |
| 文件监听 | WatchMonitor |
| – | – |
| 文件 | |
| 文件读取 | FileReader |
| 文件写入 | FileWriter |
| 文件追加 | FileAppender |
| 文件跟随 | Tailer |
| 文件名工具 | FileNameUtil |
| – | – |
| 资源 | |
| 资源工具 | ResourceUtil |
| ClassPath资源访问 | ClassPathResource |
| – | – |
| 工具类 | |
| 字符串工具 | StrUtil |
| 16进制工具 | HexUtil |
| Escape工具 | EscapeUtil |
| Hash算法 | HashUtil |
| URL工具 | URLUtil |
| XML工具 | XmlUtil |
| 对象工具 | ObjectUtil |
| 反射工具 | ReflectUtil |
| 泛型类型工具 | TypeUtil |
| 分页工具 | PageUtil |
| 剪贴板工具 | ClipboardUtil |
| 类工具 | ClassUtil |
| 类加载工具 | ClassLoaderUtil |
| 枚举工具 | EnumUtil |
| 命令行工具 | RuntimeUtil |
| 数字工具 | NumberUtil |
| 数组工具 | ArrayUtil |
| 随机工具 | RandomUtil |
| 唯一ID工具 | IdUtil |
| 压缩工具 | ZipUtil |
| 引用工具 | ReferenceUtil |
| 正则工具 | ReUtil |
| 身份证工具 | IdcardUtil |
| 信息脱敏工具 | DesensitizedUtil |
| 社会信用代码工具 | CreditCodeUtil |
| SPI加载工具 | ServiceLoaderUtil |
| – | – |
| 语言特性 | |
| 概述 | |
| HashMap扩展 | Dict |
| 单例工具 | Singleton |
| 断言 | Assert |
| 二进码十进数 | BCD |
| 控制台打印封装 | Console |
| 字段验证器 | Validator |
| 字符串格式化 | StrFormatter |
| – | – |
| 树结构 | |
| 树结构工具-TreeUtil | |
| – | – |
| JavaBean | |
| Bean工具 | BeanUtil |
| DynaBean | |
| 表达式解析 | BeanPath |
| Bean描述 | BeanDesc |
| 空检查属性获取 | Opt |
| – | – |
| 集合类 | |
| 集合工具 | CollUtil |
| 列表工具 | ListUtil |
| terator工具 | IterUtil |
| 有界优先队列 | BoundedPriorityQueue |
| 线程安全的HashSet | ConcurrentHashSet |
| 集合串行流工具类 | CollStreamUtil |
| 行遍历器 | Linelter |
| – | – |
| Map | |
| Map工具 | MapUtil |
| 双向查找Map | BiMap |
| 可重复键值Map | TableMap |
| – | – |
| code编码 | |
| Base62编码解码 | Base62 |
| Base64编码解码 | Base64 |
| Base32编码解码 | Base32 |
| 莫斯尔电码 | Morse |
| BCD码 | |
| 回转N位密码 | Rot |
| Runycode | 实现punyCode.md |
| – | – |
| 文本操作 | |
| CSV文件处理工具 | CsvUtil |
| 可复用字符串生成器 | StrBuilder |
| Unicode编码转换工具 | UnicodeUtil |
| 字符串切割 | StrSpliter |
| – | – |
| 注解 | |
| 注解工具 | AnnotationUtil |
| – | – |
| 比较器 | |
| 比较工具 | CompareUtil |
| 异常工具 | ExceptionUtil |
| – | – |
| 异常 | |
| 异常工具 | ExcePtionUtil |
| 其他异常封装 | |
| – | – |
| 数学 | |
| 数学相关 | MathUtil |
| – | – |
| 线程和并发 | |
| 线程工具 | ThreadUtil |
| 自定义线程池 | ExecutorBuilder |
| 高并发测试 | ConcurrencyTester |
| – | – |
| 图片 | |
| 图片工具 | ImgUtil |
| 图片编辑器 | Img |
| – | – |
| 网络 | |
| 网络工具 | NetUtil |
| URL生成器 | UrlBuilder |
| – | – |
| 源码编译工具 | CompilerUtil.md |
| – | – |
| 配置文件 | |
| 设置文件 | setting |
| properties扩展 | prop |
| – | – |
| 日志工厂 | LogFactory |
| 静态调用日志 | StaticLog |
| – | – |
| 缓存(Hutool-cache) | |
| 缓存工具 | CacheUtil |
| 先入先出 | FIFOCache |
| 最少使用 | LFUCache |
| 最近最久未使用 | LRUCache |
| 超时 | TimedCache |
| 弱引用 | WeakCache |
| 文件缓存 | FileCache |
| – | – |
| JSON(Hutool-json) | |
| JSON工具-JSONUtil | |
| JSON对象-JSONObject | |
| JSON数组-JSONArray | |
| – | – |
| 加密解密(Hutool-crypto) | |
| 加密解密工具 | SecureUtil |
| 对称加密 | SymmetricCrypto |
| 非对称加密 | AsymmetricCrypto |
| 摘要加密 | Digester |
| 消息认证码算法 | HMac |
| 签名和验证 | Sign |
| 国密算法工具 | SmUtil |
| – | – |
| HTTP客户端(Hutool-http) | |
| Http客户端工具类 | HttpUtil |
| Http请求 | HttpRequest |
| Http响应 | HttpResponse |
| HTML工具类 | HtmlUtil |
| – | – |
| UA工具类 | UserAgentUtil |
| 定时任务(Hutool-cron) | |
| 全局定时任务 | CronUtil |
| 扩展(Hutool-extra) | |
| 邮件工具 | MailUtil |
| 二维码工具 | QrCodeUtil |
| Servlet工具 | ServletUtil |
| – | – |
| 缓存(Hutool-cache) | |
| 缓存工具 | CacheUtil |
| 先入先出 | FIFOCache |
| 最少使用 | LFUCache |
| 最近最久未使用 | LRUCache |
| 超时 | TimedCache |
| 弱引用 | WeakCache |
| 文件缓存 | FileCache |
| – | – |
| 模板引擎 | |
| 模板引擎封装 | TemplateUtil |
| – | – |
| Spring | |
| Spring工具 | SpringUtil |
| – | – |
| Cglib | |
| Cglib工具 | CglibUtil |
| 拼音工具 | PinyinUtil |
| 布隆过滤(Hutool-bloomFilter) | |
| 切面(Hutool-aop) | |
| 切面代理工具 | ProxyUtil |
| 脚本(Hutool-script) | |
| Script工具 | ScriptUtil |
| Office文档操作(Hutool-poi) | |
| – | – |
| Excel工具 | ExcelUtil |
| Excel读取 | ExcelReader |
| 流方式读取Excel2003 | Excel03SaxReader |
| 流方式读取Excel2007 | Excel07SaxReader |
| Excel生成 | ExcelWriter |
| Excel大数据生成 | BigExcelWriter |
| Word生成 | Word07Writer |
最后
以上就是故意歌曲最近收集整理的关于常用工具类Hutool的学习使用简介的全部内容,更多相关常用工具类Hutool内容请搜索靠谱客的其他文章。
发表评论 取消回复