Hutool

1、Hutool是什么

Hutool 是一个小而全的 Java 工具类库,通过静态方法封装,降低相关 API 的学习成本,提高工作效率,它帮助我们简化每一行代码,避免重复造轮子。如果你有需要用到某些工具方法的时候,可以在 Hutool 里面找找,可能就有你需要的工具方法。其依赖坐标如下:

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

需要注意的是Hutool中的工具类非常多,有别的需要可以参考 Hutool 官方网站:Hutool — 🍬A set of tools that keep Java sweet. 

2、常用工具类

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

2.2 日期时间对象-DateTime

日期时间对象,DateTime对象包含众多的构造方法,代码如下:

//新建对象
Date date = new Date();        
//new方式创建
DateTime time = new DateTime(date);
Console.log(time);
//of方式创建
DateTime now = DateTime.now();
DateTime dt = DateTime.of(date);

//使用对象
DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);     
//年,结果:2017
int year = dateTime.year();
//季度(非季节),结果:Season.SPRING
Season season = dateTime.seasonEnum();
//月份,结果:Month.JANUARY
Month month = dateTime.monthEnum();
//日,结果:5
int day = dateTime.dayOfMonth();

//对象的可变性
DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);

//默认情况下DateTime为可变对象,此时offset == dateTime
DateTime offset = dateTime.offset(DateField.YEAR, 0);
//设置为不可变对象后变动将返回新对象,此时offset != dateTime
dateTime.setMutable(false);
offset = dateTime.offset(DateField.YEAR, 0);

// 格式化为字符串
DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
//结果:2017-01-05 12:34:23
String dateStr = dateTime.toString();
//结果:2017/01/05

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

2.4 字符串工具类 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);

2.5 数字处理工具类 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);

2.6 JavaBean的工具类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);

2.7 集合操作的工具类 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);

2.8 Map操作工具类 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);

2.9 数组工具-ArrayUtil

数组工具类主要是解决对象数组(包括包装类型数组)和原始类型数组使用方法不统一的问题,代码如下:

//判断空 和 非空
int[] a = {};
int[] b = null;
ArrayUtil.isEmpty(a);
ArrayUtil.isEmpty(b);

//判断非空
int[] a = {1,2};
ArrayUtil.isNotEmpty(a);

//新建泛型数组
String[] newArray = ArrayUtil.newArray(String.class, 3);

//泛型数组调用原生克隆
Integer[] b = {1,2,3};
Integer[] cloneB = ArrayUtil.clone(b);
Assert.assertArrayEquals(b, cloneB);

//非泛型数组(原始类型数组)调用第二种重载方法
int[] a = {1,2,3};
int[] clone = ArrayUtil.clone(a);
Assert.assertArrayEquals(a, clone);

2.10 唯一ID工具-IdUtil

唯一ID生成器的工具类,涵盖了:UUID 、 ObjectId(MongoDB)、Snowflake(Twitter),代码如下:

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

2.11 IO工具类-IoUtil

IO工具类的存在主要针对InputStream、OutputStream、Reader、Writer封装简化,并对NIO相关操作做封装简化,代码如下:

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

2.12 加密解密工具类 SecureUtil

加密解密工具类,可用于MD5加密

//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:{}", md5Str);

2.13 验证码工具类 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();
}

2.14 分页工具-PageUtil

分页工具类并不是数据库分页的封装,而是分页方式的转换

//transToStartEnd 将页数和每页条目数转换为开始位置和结束位置。 此方法用于不包括结束位置的分页方法
int[] startEnd1 = PageUtil.transToStartEnd(0, 10);//[0, 10]
int[] startEnd2 = PageUtil.transToStartEnd(1, 10);//[10, 20]

//根据总数计算总页数
int totalPage = PageUtil.totalPage(20, 3);//7

2.15 Java反射工具类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);

2.16 注解工具类 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);

2.17 ClassPath资源访问 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);

2.18 16进制工具-HexUtil

16进制一般针对无法显示的一些二进制进行显示,常用于: 1、图片的字符串表现形式 2、加密解密 3、编码转换

// HexUtil主要以encodeHex和decodeHex两个方法为核心,提供一些针对字符串的重载方法
String str = "我是一个字符串";

String hex = HexUtil.encodeHexStr(str, CharsetUtil.CHARSET_UTF_8);

//hex是:
//e68891e698afe4b880e4b8aae5ad97e7aca6e4b8b2

String decodedStr = HexUtil.decodeHexStr(hex);

//解码后与str相同

2.19 URL工具-URLUtil

URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。在Java中,也可以使用URL表示Classpath中的资源(Resource)地址

//获取URL对象
URLUtil.url 通过一个字符串形式的URL地址创建对象
URLUtil.getURL 主要获得ClassPath下资源的URL,方便读取Classpath下的配置文件等信息

//URLUtil.normalize 标准化化URL链接。对于不带http://头的地址做简单补全
String url = "http://www.hutool.cn//aaa/bbb";
// 结果为:http://www.hutool.cn/aaa/bbb
String normalize = URLUtil.normalize(url);

url = "http://www.hutool.cn//aaa/\\bbb?a=1&b=2";
// 结果为:http://www.hutool.cn/aaa/bbb?a=1&b=2
normalize = URLUtil.normalize(url);

2.20 随机工具-RandomUtil

RandomUtil主要针对JDK中Random对象做封装

//例如我们想产生一个[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 权重随机生成器,传入带权重的对象,然后根据权重随机获取对象

2.21 身份证工具-IdcardUtil

对身份证的验证主要是正则方式(位数,数字范围等),工具中主要的方法包括:

  • isValidCard 验证身份证是否合法

  • convert15To18 身份证15位转18位

  • getBirthByIdCard 获取生日

  • getAgeByIdCard 获取年龄

  • getYearByIdCard 获取生日年

  • getMonthByIdCard 获取生日月

  • getDayByIdCard 获取生日天

  • getGenderByIdCard 获取性别

  • getProvinceByIdCard 获取省份

String ID_18 = "321083197812162119";
String ID_15 = "150102880730303";

//是否有效
boolean valid = IdcardUtil.isValidCard(ID_18);
boolean valid15 = IdcardUtil.isValidCard(ID_15);

//转换
String convert15To18 = IdcardUtil.convert15To18(ID_15);
Assert.assertEquals(convert15To18, "150102198807303035");

//年龄
DateTime date = DateUtil.parse("2017-04-10");
        
int age = IdcardUtil.getAgeByIdCard(ID_18, date);
Assert.assertEquals(age, 38);

int age2 = IdcardUtil.getAgeByIdCard(ID_15, date);
Assert.assertEquals(age2, 28);

//生日
String birth = IdcardUtil.getBirthByIdCard(ID_18);
Assert.assertEquals(birth, "19781216");

String birth2 = IdcardUtil.getBirthByIdCard(ID_15);
Assert.assertEquals(birth2, "19880730");

//省份
String province = IdcardUtil.getProvinceByIdCard(ID_18);
Assert.assertEquals(province, "江苏");

String province2 = IdcardUtil.getProvinceByIdCard(ID_15);
Assert.assertEquals(province2, "内蒙古");

2.22 信息脱敏工具-DesensitizedUtil

在数据处理或清洗中,可能涉及到很多隐私信息的脱敏工作,所谓脱敏就是隐藏掉信息中的一部分关键信息,用*代替

// 5***************1X
DesensitizedUtil.idCardNum("51343620000320711X", 1, 2);

// 180****1999
DesensitizedUtil.mobilePhone("18049531999");

// 比如密码,只保留了位数信息,**********
DesensitizedUtil.password("1234567890");
  • 10
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

真滴book理喻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值