• 常用工具类Hutool的学习使用


    简介

    中文官网:https://plus.hutool.cn/docs/
    Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

    Hutool的目标是使用一个工具方法代替一段复杂代码,从而最大限度的避免“复制粘贴”代码的问题,彻底改变我们写代码的方式。

    包含组件

    模块介绍
    hutool-aopJDK动态代理封装,提供非IOC下的切面支持
    hutool-bloomFilter布隆过滤,提供一些Hash算法的布隆过滤
    hutool-cache简单缓存实现
    hutool-core核心,包括Bean操作、日期、各种Util等
    hutool-cron定时任务模块,提供类Crontab表达式的定时任务
    hutool-crypto加密解密模块,提供对称、非对称和摘要算法封装
    hutool-dbJDBC封装后的数据操作,基于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-jsonJSON实现
    hutool-captcha图片验证码实现
    hutool-poi针对POI中Excel和Word的封装
    hutool-socket基于Java的NIO和AIO的Socket封装
    hutool-jwtJSON Web Token (JWT)封装实现

    导入

    <dependency>
    
            <groupId>cn.hutool</groupId>
    
            <artifactId>hutool-all</artifactId>
    
            <version>5.8.0.M4</version>
    
    </dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    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));
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    结果

    true
    true
    false
    true
    
    • 1
    • 2
    • 3
    • 4

    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);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    SecureUtil(加密解密工具)

    主要是在登录的时候还有修改密码的时候用到的,因为数据库里面的密码是 md5 加密处理的,所以登录的时候需要先加密之后再到数据库进行查询,使用 Hutool 的话,只需要调用 SecureUtil 中的 md5 方法就可以了。

    user = userService.userLoginByName(username,SecureUtil.md5(password));
    
    • 1

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    等等因为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
    线程安全的HashSetConcurrentHashSet
    集合串行流工具类CollStreamUtil
    行遍历器Linelter
    Map
    Map工具MapUtil
    双向查找MapBiMap
    可重复键值MapTableMap
    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
    流方式读取Excel2003Excel03SaxReader
    流方式读取Excel2007Excel07SaxReader
    Excel生成ExcelWriter
    Excel大数据生成BigExcelWriter
    Word生成Word07Writer
  • 相关阅读:
    智安网络|边缘计算与分布式存储:数字化时代的新趋势
    synchronized原理-字节码分析、对象内存结构、锁升级过程、Monitor
    单元测试(JUint)
    Java#25(常见算法: 查找算法)
    Android笔记(七)Android JetPack Compose组件搭建Scaffold脚手架
    Flutter 实现光影变换的立体旋转效果
    java算法第21天 | 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先
    【CVPR 2021】Cylinder3D:用于LiDAR点云分割的圆柱体非对称3D卷积网络
    保研CS/软件工程/通信专业问题汇总(搜集和自己遇到的)
    数说故事官网全新升级,高效赋能业务场景
  • 原文地址:https://blog.csdn.net/weixin_53998054/article/details/126133718