Hutool工具类常用工具

发布时间 2023-04-18 11:29:20作者: 企业级理解

介绍

 

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

 

Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。

Hutool如何改变我们的coding方式?

以计算MD5为例:
【以前】打开搜索引擎 -> 搜“Java MD5加密” -> 打开某篇博客-> 复制粘贴 -> 改改好用
【现在】引入Hutool -> SecureUtil.md5()

组件

Maven 

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.18</version>
</dependency>

注意 Hutool 5.x支持JDK8+,对Android平台没有测试,不能保证所有工具类或工具方法可用。 如果你的项目使用JDK7,请使用Hutool 4.x版本(不再更新)

常用工具间类

1.生成图形验证码输出流——CaptchaUtil

@RestController
public class CaptchaController {
    @GetMapping("/getCaptcha")
    @ApiOperation(value = "获取验证码")
    public void getCaptcha(HttpServletResponse response) {
        //生成验证码图片
        LineCaptcha circleCaptcha = CaptchaUtil.createLineCaptcha(200/**/, 100/**/, 4/*验证码显示几个*/, 50/*有几个线段*/);
        //告诉浏览器输出内容为jpeg类型的图片
        response.setContentType("image/jpeg");
        //禁止浏览器缓存
        response.setHeader("Pragma", "No-cache");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            circleCaptcha.write(outputStream);
            String code = circleCaptcha.getCode();
            Console.log(code);
            //关闭流
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 2.信息脱敏——DesensitizedUtil

//身份证
String idCard = DesensitizedUtil.idCardNum("4136200003265871X", 1, 2);
System.out.println("加密后身份证:"+idCard);
//手机号码
String mobile = DesensitizedUtil.mobilePhone("18569195966");
System.out.println("加密后手机号码:"+mobile);
//密码
String passWord = DesensitizedUtil.password("123456789");
System.out.println("加密后密码:"+passWord);

 hutool目前支持脱敏系列有

用户id
中文姓名
身份证号
座机号
手机号
地址
电子邮件
密码
中国大陆车牌,包含普通车辆、新能源车辆
银行卡

3.MD5加密——SecureUtil

String s = SecureUtil.md5("123456");
System.out.println("加密后:"+s);

 4.http工具类发送http请求——HttpRequest

public void testHttps() throws Exception {
            JSONObject json = new JSONObject();
            json.put("username", "1332788xxxxxx");
            json.put("password", "123456.");
            String result = HttpRequest.post("https://api2.hutool.cn/1/users")
                    .header("Content-Type", "application/json")
                    .header("X-Bmob-Application-Id","2f0419a31f9casdfdsf431f6cd297fdd3e28fds4af")
                    .header("X-Bmob-REST-API-Key","1e03efdas82178723afdsafsda4be0f305def6708cc6")
                    .body(String.valueOf(json))
                    .execute().body();
            System.out.println(result);
    }

5.日期时间工具类——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);

6.类型转换工具——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);

7.字符串工具类——StrUtil

//判断是否为空字符串
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);

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);

9.JavaBean的工具类 BeanUtil

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);

10.唯一ID工具-IdUtil

// UUID
//生成的UUID是带-的字符串,类似于:a5c8a5e8-df2b-4706-bea4-08d0939410e3
String uuid = IdUtil.randomUUID();

//生成的是不带-的字符串,类似于:b17f24ff026d40949c85a24f4f375d42
String simpleUUID = IdUtil.simpleUUID();

//ObjectId
//生成类似:5b9e306a4df4f8c54a39fb0c
String id = ObjectId.next();

//方法2:从Hutool-4.1.14开始提供
String id2 = IdUtil.objectId();

//Snowflake
//参数1为终端ID
//参数2为数据中心ID
Snowflake snowflake = IdUtil.getSnowflake(1, 1);
long id = snowflake.nextId();

11.IO工具类-IoUtil

//文件流拷贝
BufferedInputStream in = FileUtil.getInputStream("d:/test.txt");
BufferedOutputStream out = FileUtil.getOutputStream("d:/test2.txt");
long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);

12.ClassPath资源访问 ClassPathResource

 

//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);

 

13.随机工具-RandomUtil

 

//例如我们想产生一个[10, 100)的随机数
int c = RandomUtil.randomInt(10, 100);

// 随机bytes,一般用于密码或者salt生成
byte[] c = RandomUtil.randomBytes(10);

//随机获得列表中的一定量的不重复元素,返回Set
Set<Integer> set = RandomUtil.randomEleSet(CollUtil.newArrayList(1, 2, 3, 4, 5, 6), 2);

RandomUtil.randomString 获得一个随机的字符串(只包含数字和字符)
RandomUtil.randomNumbers 获得一个只包含数字的字符串
RandomUtil.weightRandom 权重随机生成器,传入带权重的对象,然后根据权重随机获取对象

 

 

 

 

上边就是比较常用的hutool工具类方法了