赞
踩
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,它帮助我们简化每一行代码,避免重复造轮子。如果你有需要用到某些工具方法的时候,可以在Hutool里面找找,可能就有你需要的工具方法。官方地址
Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类,同时提供以下组件:
模块 | 介绍 |
---|---|
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.7.13</version>
</dependency>
@Test void DateUtilTest() { //普通创建时间 Date date = new Date(); String dateString = "2022-10-18 17:16:57"; log.info(date.toString());//Thu Oct 27 15:01:56 CST 2022 //使用DateTime创建时间 date = DateUtil.date(); log.info(date.toString());//2022-10-27 15:01:56 //创建日历 Calendar instance = Calendar.getInstance(); log.info(instance.toString()); //Calendar转Date date = DateUtil.date(instance); log.info(date.toString());//2022-10-27 15:12:49 //Calendar转Date date = DateUtil.date(System.currentTimeMillis()); log.info(date.toString());//2022-10-27 15:12:49 //自动识别格式转换 date = DateUtil.parse(dateString); log.info(date.toString());//2022-10-18 17:16:57 //自定义格式化转换 date = DateUtil.parse(dateString, "yyyy-MM-dd"); log.info(date.toString());//2022-10-18 00:00:00 //格式化输出日期 dateString = DateUtil.format(date, "yyyy-MM-dd"); log.info(dateString);//022-10-18 //获得年的部分 Integer year = DateUtil.year(date); log.info(year.toString());//2022 //获得月份,从0开始计数 Integer month = DateUtil.month(date); log.info(month.toString());//9 //获取某天的开始、结束时间 Date beginOfDay = DateUtil.beginOfDay(date); log.info(beginOfDay.toString());//2022-10-18 00:00:00 Date endOfDay = DateUtil.endOfDay(date); log.info(endOfDay.toString());//2022-10-18 23:59:59 //计算偏移后的日期时间 Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2); log.info(newDate.toString());//2022-10-20 00:00:00 //计算日期时间之间的偏移量 Long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY); log.info(betweenDay.toString());//2 }
@Test void DateTimeTest() { //普通创建时间 Date date = new Date(); //new方式创建 DateTime time = new DateTime(date); log.info(time.toString());//2022-10-28 09:18:41 //of方式创建 DateTime now = DateTime.now(); log.info(now.toString());//2022-10-28 09:18:41 DateTime dt = DateTime.of(date); log.info(dt.toString());//2022-10-28 09:18:41 //使用对象 DateTime dateTime = new DateTime("2022年11月11日12时13分14秒", DatePattern.CHINESE_DATE_TIME_FORMAT);//yyyy年MM月dd日HH时mm分ss秒 log.info(dateTime.toString());//2022-11-11 12:13:14 //年,结果:2022 Integer year = dateTime.year(); log.info(year.toString()); //月份,结果:Month.NOVEMBER Month month = dateTime.monthEnum(); log.info(month.toString());//NOVEMBER //日,结果:11 Integer day = dateTime.dayOfMonth(); log.info(day.toString());//11 //对象的可变性 DateTime dateTime2 = new DateTime("2022-11-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT); //默认情况下DateTime为可变对象,此时offset == dateTime DateTime offset = dateTime2.offset(DateField.YEAR, 0); log.info(offset.toString());//2022-11-05 12:34:23 log.info(String.valueOf(offset == dateTime2));//true //设置为不可变对象后变动将返回新对象,此时offset != dateTime dateTime2.setMutable(false); offset = dateTime2.offset(DateField.YEAR, 0); log.info(offset.toString());//2022-11-05 12:34:23 log.info(String.valueOf(offset == dateTime2));//false }
@Test void ConvertTest() { //转换为字符串 int a = 1; String aStr = Convert.toStr(a); log.info(aStr); //转换为指定类型数组 String[] b = {"1", "2", "3", "4"}; Integer[] bArr = Convert.toIntArray(b); ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); String s = Convert.toStr(arrayList); log.info(s);//[a, b, c] //转换为日期对象 String dateStr = "2022-11-06"; Date date = Convert.toDate(dateStr); log.info(date.toString());//2022-11-06 00:00:00 String dateStr2 = "2022年11月06日"; Date date2 = Convert.toDate(dateStr2); log.info(date2.toString());//2022-11-06 00:00:00 //转换为列表 String[] strArr = {"1", "2", "3", "4"}; List<String> stringList = Convert.toList(String.class, strArr); log.info(stringList.toString()); List<Integer> integerList = Convert.toList(Integer.class, strArr); log.info(integerList.toString()); }
@Test void StrUtilTest() { //判断是否为空字符串 String str = "test"; log.info(String.valueOf(StrUtil.isEmpty(str)));//false log.info(String.valueOf(StrUtil.isNotEmpty(str)));//true log.info(String.valueOf(StrUtil.isBlank(str)));//false log.info(String.valueOf(StrUtil.isNotBlank(str)));//true //isBlank与isEmpty的区别 String str2 = " "; log.info(String.valueOf(StrUtil.isEmpty(str2)));//false log.info(String.valueOf(StrUtil.isBlank(str2)));//true //去除字符串的前后缀 String s = StrUtil.removeSuffix("a.jpg", ".jpg"); log.info(s);//a String s1 = StrUtil.removePrefix("a.jpg", "a."); log.info(s1);//jpg //格式化字符串 String template = "这只是个占位符:{}"; String s3 = StrUtil.format(template, "我是占位符12138"); log.info(s3);//这只是个占位符:我是占位符12138 }
@Test void NumberUtilTest() { Double n1 = 1.234; Double n2 = 1.234; Double result; //对float、double、BigDecimal做加减乘除操作 result = NumberUtil.add(n1, n2); log.info(result.toString());//2.468 result = NumberUtil.sub(n1, n2); log.info(result.toString());//0.0 result = NumberUtil.mul(n1, n2); log.info(result.toString());//1.522756 result = NumberUtil.div(n1, n2); log.info(result.toString());//1.0 //保留两位小数 BigDecimal roundNum = NumberUtil.round(n1, 2); log.info(roundNum.toString());//1.23 String n3 = "1.234"; //判断是否为数字、整数、浮点数 Boolean number = NumberUtil.isNumber(n3); log.info(number.toString());//true Boolean integer = NumberUtil.isInteger(n3); log.info(integer.toString());//false Boolean aDouble = NumberUtil.isDouble(n3); log.info(aDouble.toString());//true }
@Test void JavaBeanTest() { People people = new People(); people.setId(1); people.setName("小米"); people.setJgId(1001); //Bean转Map Map<String, Object> map = BeanUtil.beanToMap(people); log.info(map.toString());//{id=1, name=小米, jgId=1001} //Map转Bean People mapToBean = BeanUtil.mapToBean(map, People.class, false); log.info(mapToBean.toString());//People(id=1, name=小米, jgId=1001) //Bean属性拷贝 People copyPeople = new People(); BeanUtil.copyProperties(mapToBean, copyPeople); log.info(copyPeople.toString());//People(id=1, name=小米, jgId=1001) }
@Test void CollUtilTest() { //数组转换为列表 String[] array = new String[]{"a", "b", "c", "d", "e"}; List<String> list = CollUtil.newArrayList(array); //join:数组转字符串时添加连接符号 String joinStr = CollUtil.join(list, ","); log.info(joinStr); //将以连接符号分隔的字符串再转换为列表 List<String> splitList = StrUtil.split(joinStr, ','); log.info(splitList.toString()); //创建新的Set、List HashSet<Object> newHashSet = CollUtil.newHashSet(); ArrayList<Object> newList = CollUtil.newArrayList(); //判断列表是否为空 Boolean empty = CollUtil.isEmpty(list); log.info(empty.toString());//false }
//将多个键值对加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
});
//判断Map是否为空
Boolean empty = MapUtil.isEmpty(map);
log.info(empty.toString());//false
Boolean notEmpty = MapUtil.isNotEmpty(map);
log.info(notEmpty.toString());//true
@Test void ArrayUtilTest() { //判断空 和 非空 int[] a = {}; int[] b = null; Boolean empty = ArrayUtil.isEmpty(a); log.info(empty.toString());//true Boolean empty1 = ArrayUtil.isEmpty(b); log.info(empty1.toString());//true //判断非空 int[] a2 = {1, 2}; Boolean notEmpty = ArrayUtil.isNotEmpty(a2); log.info(notEmpty.toString());//true //新建泛型数组 String[] newArray = ArrayUtil.newArray(String.class, 3); log.info(newArray.toString());// //泛型数组调用原生克隆 Integer[] b3 = {1, 2, 3}; Integer[] cloneB = ArrayUtil.clone(b3); log.info(Arrays.deepToString(cloneB));//[1, 2, 3] //非泛型数组(原始类型数组)调用第二种重载方法 int[] a3 = {1, 2, 3}; int[] cloneA = ArrayUtil.clone(a3); log.info(Arrays.toString(cloneA));//[1, 2, 3] }
@Test void IdUtilTest() { // UUID //生成的UUID是带-的字符串,类似于:a5c8a5e8-df2b-4706-bea4-08d0939410e3 String uuid = IdUtil.randomUUID(); log.info(uuid);//a9bada65-2298-4daf-a490-861938084ad6 //生成的是不带-的字符串,类似于:b17f24ff026d40949c85a24f4f375d42 String simpleUUID = IdUtil.simpleUUID(); log.info(simpleUUID);//92d6bce683bc45dd8400ce79db18b9a9 //ObjectId //生成类似:5b9e306a4df4f8c54a39fb0c String id = ObjectId.next(); log.info(id);//635b9f20e2d6c9730038d333 //方法2:从Hutool-4.1.14开始提供 String id2 = IdUtil.objectId(); log.info(id2);//635b9f20e2d6c9730038d334 //Snowflake雪花算法生成数字id //参数1为终端ID //参数2为数据中心ID Snowflake snowflake = IdUtil.getSnowflake(1, 1); Long id3 = snowflake.nextId(); log.info(id3.toString());//1585924733496492032 }
@Test
void IoUtilTest(){
//文件流拷贝
BufferedInputStream in = FileUtil.getInputStream("d:/test.txt");
BufferedOutputStream out = FileUtil.getOutputStream("d:/test2.txt");
Long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
log.info(copySize.toString());//9(字节)
}
@Test
void SecureUtilTest() {
//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
log.info(md5Str);//e10adc3949ba59abbe56e057f20f883e
}
@Test
void CaptchaUtilTest() {
//生成验证码图片
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();
}
}
@Test
void PageUtilTest(){
//transToStartEnd 将页数和每页条目数转换为开始位置和结束位置。 此方法用于不包括结束位置的分页方法
int[] startEnd1 = PageUtil.transToStartEnd(0, 10);//[0, 10]
int[] startEnd2 = PageUtil.transToStartEnd(1, 10);//[10, 20]
log.info(String.valueOf(startEnd1.length));//2
log.info(String.valueOf(startEnd2.length));//2
//根据总数计算总页数
int totalPage = PageUtil.totalPage(20, 3);//7
log.info(String.valueOf(totalPage));//7
}
@Test void ReflectUtilTest() { //获取某个类的所有方法 Method[] methods = ReflectUtil.getMethods(MyTestUtils.class); //获取某个类的指定方法 Method getIdMethod = ReflectUtil.getMethod(MyTestUtils.class, "getId"); Method sbMethod = ReflectUtil.getMethod(MyTestUtils.class, "sb"); //使用反射来创建对象 MyTestUtils pmsBrand = ReflectUtil.newInstance(MyTestUtils.class); //反射执行对象无参的方法 ReflectUtil.invoke(pmsBrand, "setId", 1L); //反射执行对象带参的方法 try { Long invoke = (Long) getIdMethod.invoke(pmsBrand); log.info(String.valueOf(invoke)); } catch (Throwable e) { e.printStackTrace(); } }
@Test void AnnotationUtilTest(){ //获取指定类、方法、字段、构造器上的注解列表 Annotation[] annotationList = AnnotationUtil.getAnnotations(MyTestUtils.class, false); log.info("annotationUtil annotations:{}", annotationList); //获取指定类型注解 Api api = AnnotationUtil.getAnnotation(MyTestUtils.class, Api.class); log.info("annotationUtil api value:{}", api.value());//MyTestUtilsApi AnnotationUtil.setValue(annotationList[0],"value","sb"); Api api2 = AnnotationUtil.getAnnotation(MyTestUtils.class, Api.class); log.info("annotationUtil api value:{}", api2.value());//sb //获取指定类型注解的值 String annotationValue = AnnotationUtil.getAnnotationValue(MyTestUtils.class, Api.class); log.info("annotationUtil api value:{}", annotationValue);//sb }
@Test
void ClassPathResourceTest(){
//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("application-dev.yml");
Properties properties = new Properties();
try {
properties.load(resource.getStream());
} catch (IOException e) {
e.printStackTrace();
}
log.info("/classPath:{}", properties);
}
@Test
void HexUtilTest(){
// HexUtil主要以encodeHex和decodeHex两个方法为核心,提供一些针对字符串的重载方法
String str = "我是一个字符串";
String hex = HexUtil.encodeHexStr(str, CharsetUtil.CHARSET_UTF_8);
log.info(hex);//e68891e698afe4b880e4b8aae5ad97e7aca6e4b8b2
String decodedStr = HexUtil.decodeHexStr(hex);
log.info(decodedStr);//解码后与str相同
}
@Test
void URLUtilTest(){
//获取URL对象
// URLUtil.url 通过一个字符串形式的URL地址创建对象
// URLUtil.getURL 主要获得ClassPath下资源的URL,方便读取Classpath下的配置文件等信息
//URLUtil.normalize 标准化化URL链接。对于不带http://头的地址做简单补全
String url = "http://www.hutool.cn//aaa/bbb";
String normalize = URLUtil.normalize(url);
log.info(normalize);//http://www.hutool.cn//aaa/bbb
url = "http://www.hutool.cn//aaa/\\bbb?a=1&b=2";
normalize = URLUtil.normalize(url);
log.info(normalize);//http://www.hutool.cn//aaa//bbb?a=1&b=2
}
@Test void RandomUtilTest(){ //例如我们想产生一个[10, 100)的随机数 int c = RandomUtil.randomInt(10, 100); log.info(String.valueOf(c));//61 // 随机bytes,一般用于密码或者salt生成 byte[] d = RandomUtil.randomBytes(10); log.info(String.valueOf(d));//[B@53747c4a //随机获得列表中的一定量的不重复元素,返回Set Set<Integer> set = RandomUtil.randomEleSet(CollUtil.newArrayList(1, 2, 3, 4, 5, 6), 2); log.info(set.toString());//[2, 1] String s = RandomUtil.randomString(2);// 获得两个随机的字符串(只包含数字和字符) log.info(s);//jo String s1 = RandomUtil.randomNumbers(2);// 获得两个只包含数字的字符串 log.info(s1);//38 List<WeightRandom.WeightObj<String>> weightList = new ArrayList<WeightRandom.WeightObj<String>>(); WeightRandom.WeightObj<String> a1 = new WeightRandom.WeightObj<String>("A", 1); WeightRandom.WeightObj<String> b1 = new WeightRandom.WeightObj<String>("B", 2); WeightRandom.WeightObj<String> c1 = new WeightRandom.WeightObj<String>("C", 3); WeightRandom.WeightObj<String> d1 = new WeightRandom.WeightObj<String>("D", 4); weightList.add(a1); weightList.add(b1); weightList.add(c1); weightList.add(d1); WeightRandom<String> stringWeightRandom = RandomUtil.weightRandom(weightList);// 权重随机生成器,传入带权重的对象,然后根据权重随机获取对象 String str = ""; int num_a = 0, num_b = 0, num_c = 0, num_d = 0; for (int i = 0; i < 100000; i++) { str = stringWeightRandom.next().toString(); switch (str) { case "A": num_a = num_a+1; break; case "B": num_b = num_b+1; break; case "C": num_c = num_c+1; break; case "D": num_d = num_d+1; break; } } log.info("A---------:{}",num_a);//A---------:10083 log.info("B---------:{}",num_b);//B---------:19955 log.info("C---------:{}",num_c);//C---------:30109 log.info("D---------:{}",num_d);//D---------:39853 }
isValidCard 验证身份证是否合法
convert15To18 身份证15位转18位
getBirthByIdCard 获取生日
getAgeByIdCard 获取年龄
getYearByIdCard 获取生日年
getMonthByIdCard 获取生日月
getDayByIdCard 获取生日天
getGenderByIdCard 获取性别
getProvinceByIdCard 获取省份
@Test void IdCardUtilTest() { String ID_18 = "321083197812162119"; String ID_15 = "150102880730303"; //是否有效 boolean valid = IdcardUtil.isValidCard(ID_18); log.info(String.valueOf(valid));//true boolean valid15 = IdcardUtil.isValidCard(ID_15); log.info(String.valueOf(valid15));//true //转换 String convert15To18 = IdcardUtil.convert15To18(ID_15); log.info(convert15To18);//150102198807303035 //年龄 DateTime date = DateUtil.parse("2000-01-01"); int age = IdcardUtil.getAgeByIdCard(ID_18, date); log.info(String.valueOf(age));//38 //生日 String birth = IdcardUtil.getBirthByIdCard(ID_18); log.info(birth);//19781216 //性别 int genderByIdCard = IdcardUtil.getGenderByIdCard(ID_18); log.info(String.valueOf(genderByIdCard));//奇数为男,偶数为女 //省份 String province = IdcardUtil.getProvinceByIdCard(ID_18); log.info(province);//江苏 }
@Test
void DesensitizedUtilTest() {
String s1 = DesensitizedUtil.idCardNum("51343620000320711X", 1, 2);
log.info(s1); // 5***************1X
String s2 = DesensitizedUtil.mobilePhone("18049531999");
log.info(s2); // 180****1999
String s3 = DesensitizedUtil.password("1234567890");
log.info(s3); // 比如密码,只保留了位数信息,**********
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。