一、介绍

Hutool

在大家日常工作中,都常常会做如下这些非常繁琐的工作:
日期与字符串转换
文件操作
转码与反转码
随机数生成
压缩与解压
编码与解码
CVS文件操作
缓存处理
加密解密
定时任务
邮件收发
二维码创建
FTP 上传与下载
图形验证码生成

等等等等

hutool 使用

要使用 hutool 很简单,用hutool-all-4.3.1.jar就行了,并且不需要第三方,只需要一个jar就够了。
不过一般使用还是以 maven 方式为多,毕竟很容易就在eclipse 和 idea 里都跑起来了,所以还是会用 maven来做。

pom.xml
导入 hutool 包

  1. <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>cn.hutool</groupId>
  6. <artifactId>hutool</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>hutool</name>
  9. <description>hutool</description>
  10. <dependencies>
  11. <dependency>
  12. <groupId>cn.hutool</groupId>
  13. <artifactId>hutool-all</artifactId>
  14. <version>4.3.1</version>
  15. </dependency>
  16. </dependencies>
  17. </project>

TestHutool
运行测试

  1. package hutool;
  2. import cn.hutool.core.date.DateUtil;
  3. import java.util.Date;
  4. public class TestHutool {
  5. public static void main(String[] args) {
  6. String dateStr = "2021-04-11 11:32:00";
  7. Date date = DateUtil.parse(dateStr);
  8. System.out.println(date);
  9. }
  10. }

二、编码工具

myHutool

自定义父类myHutool,编写通用工具类。

  1. package cn.hutool.test;
  2. import cn.hutool.core.convert.Convert;import cn.hutool.core.util.ReflectUtil;import cn.hutool.core.util.StrUtil;
  3. import java.lang.annotation.*;import java.lang.reflect.Method;
  4. import static java.lang.annotation.ElementType.METHOD;import static java.lang.annotation.ElementType.TYPE;
  5. public class myHutool {
  6. private String preComment = null;
  7. private void c(String msg){
  8. System.out.printf("\t备注: %s%n",msg);
  9. }
  10. public void p1(String type1, Object value1, String type2, Object value2) {
  11. p(type1, value1, type2, value2, "format1");
  12. }
  13. public void p2(String type1, Object value1, String type2, Object value2) {
  14. p(type1, value1, type2, value2, "format2");
  15. }
  16. public void p3(String type1, Object value1) {
  17. p(type1, value1, "", "", "format3");
  18. }
  19. public void p(String type1, Object value1, String type2, Object value2, String format) {
  20. try {
  21. throw new Exception();
  22. } catch (Exception e) {
  23. String methodName = getTestMethodName(e.getStackTrace());
  24. Method method = ReflectUtil.getMethod(this.getClass(),methodName);
  25. TestHex.Comment annotation = method.getAnnotation(TestHex.Comment.class);
  26. if (annotation != null){
  27. String comment = annotation.value();
  28. if (!comment.equals(preComment)){
  29. System.out.printf("%n%s 例子: %n%n",comment);
  30. preComment = comment;
  31. }
  32. }
  33. }
  34. int padLength = 12;
  35. type1 = StrUtil.padEnd(type1,padLength, Convert.toSBC(" ").charAt(0));
  36. type2 = StrUtil.padEnd(type2,padLength,Convert.toSBC(" ").charAt(0));
  37. if("format1".equals(format)) {
  38. System.out.printf("\t%s的:\t\"%s\" %n\t被转换为----->%n\t%s的 :\t\"%s\" %n%n",type1,value1, type2, value2);
  39. }
  40. if("format2".equals(format)) {
  41. System.out.printf("\t基于 %s:\t\"%s\" %n\t获取 %s:\t\"%s\"%n%n",type1,value1, type2, value2);
  42. }
  43. if("format3".equals(format)) {
  44. System.out.printf("\t%s:\t\"%s\" %n\t%n",type1,value1);
  45. }
  46. }
  47. public String getTestMethodName(StackTraceElement[] stackTrace) {
  48. for (StackTraceElement stackTraceElement : stackTrace){
  49. String methodName = stackTraceElement.getMethodName();
  50. if (methodName.startsWith("test"))
  51. return methodName;
  52. }
  53. return null;
  54. }
  55. @Target({METHOD,TYPE})
  56. @Retention(RetentionPolicy.RUNTIME)
  57. @Inherited
  58. @Documented
  59. public @interface Comment {
  60. String value();
  61. }
  62. }

hutool 16进制工具

TestHex

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.HexUtil;import org.junit.Test;
  3. import java.awt.*;
  4. public class TestHex extends myHutool {
  5. @Test
  6. @Comment("判断是否是十六进制")
  7. public void test1(){
  8. String s1 = "12";
  9. boolean b1 = HexUtil.isHexNumber(s1);
  10. String s2 = "0x12";
  11. boolean b2 = HexUtil.isHexNumber(s2);
  12. p2("字符串",s1,"是否是十六进制",b1);
  13. p2("字符串",s2,"是否是十六进制",b2);
  14. }
  15. @Test
  16. @Comment("字符串和十六进制互相转换")
  17. public void test2(){
  18. String s1 = "hutool.cn - java教程";
  19. String s2 = HexUtil.encodeHexStr(s1);
  20. String s3 = HexUtil.decodeHexStr(s2);
  21. p2("原数据",s1,"十六机制编码",s2);
  22. p2("十六进制",s2, "十六机制解码",s3);
  23. }
  24. @Test
  25. @Comment("颜色转换")
  26. public void test3(){
  27. Color color1 = Color.red;
  28. String s1 = HexUtil.encodeColor(color1);
  29. String s2 = "#112233";
  30. Color color2 = HexUtil.decodeColor(s2);
  31. p2("颜色对象1",color1, "字符串",s1);
  32. p2("字符串",s2, "颜色对象2",color2);
  33. }
  34. }

hutool 转义工具

TestEscape

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.EscapeUtil;import org.junit.Test;
  3. public class TestEscape extends myHutool {
  4. @Test
  5. @Comment("转义与反转义")
  6. public void test2(){
  7. String s1 = "<script>location.href='http://baidu.com';</script>";
  8. String s2 = EscapeUtil.escapeHtml4(s1);
  9. String s3 = EscapeUtil.unescapeHtml4(s2);
  10. p2("原数据",s1,"转义后",s2);
  11. p2("转义后",s2,"原数据",s3);
  12. }
  13. }

hutool Hash工具

TestHash

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.HashUtil;import org.junit.Test;
  3. public class TestHash extends myHutool {
  4. @Test
  5. @Comment("各种各样的hash算法")
  6. public void test2(){
  7. String s = "hutool- java教程";
  8. int number = 12;
  9. char [] s2= "df".toCharArray();
  10. int []aaa= {1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9};
  11. long hash1 = HashUtil.additiveHash(s,Integer.MAX_VALUE);
  12. long hash2 = HashUtil.rotatingHash(s,Integer.MAX_VALUE);
  13. long hash3 = HashUtil.oneByOneHash(s);
  14. long hash4 = HashUtil.bernstein(s);
  15. long hash5 = HashUtil.universal(s2,1,aaa); //怎么调用?站长不会调用。。。颜面~~~
  16. // long hash6 = HashUtil.zobrist(s);
  17. long hash7 = HashUtil.fnvHash(s);
  18. long hash8 = HashUtil.intHash(number);
  19. long hash9 = HashUtil.rsHash(s);
  20. long hash10 = HashUtil.jsHash(s);
  21. long hash11 = HashUtil.pjwHash(s);
  22. long hash12 = HashUtil.elfHash(s);
  23. long hash13 = HashUtil.bkdrHash(s);
  24. long hash14 = HashUtil.sdbmHash(s);
  25. long hash15 = HashUtil.djbHash(s);
  26. long hash16 = HashUtil.dekHash(s);
  27. long hash17 = HashUtil.apHash(s);
  28. long hash18 = HashUtil.tianlHash(s);
  29. long hash19 = HashUtil.javaDefaultHash(s);
  30. long hash20 = HashUtil.mixHash(s);
  31. p2("原数据",s, "加法算法对应的哈希值", hash1);
  32. p2("原数据",s, "旋转算法对应的哈希值", hash2);
  33. p2("原数据",s, "一次一个算法对应的哈希值", hash3);
  34. p2("原数据",s, "Bernstein's算法对应的哈希值", hash4);
  35. p2("原数据",s, " Universal 算法对应的哈希值", hash5);// p2("原数据",s, " Zobrist 算法对应的哈希值", hash6);
  36. p2("原数据",s, " 改进的32位FNV 算法对应的哈希值", hash7);
  37. p2("原数据",s, "Thomas Wang的整数算法对应的哈希值", hash8);
  38. p2("原数据",s, "RS算法对应的哈希值", hash9);
  39. p2("原数据",s, "JS算法对应的哈希值", hash10);
  40. p2("原数据",s, "PJ算法对应的哈希值", hash11);
  41. p2("原数据",s, "ELF算法对应的哈希值", hash12);
  42. p2("原数据",s, "BKDR算法对应的哈希值", hash13);
  43. p2("原数据",s, "SDBM算法对应的哈希值", hash14);
  44. p2("原数据",s, "DJB算法对应的哈希值", hash15);
  45. p2("原数据",s, "DEK算法对应的哈希值", hash16);
  46. p2("原数据",s, "AP算法对应的哈希值", hash17);
  47. p2("原数据",s, "TianL算法对应的哈希值", hash18);
  48. p2("原数据",s, "JAVA自己带算法对应的哈希值", hash19);
  49. p2("原数据",s, "混合算法对应的哈希值", hash20);
  50. }
  51. }

注意:

Universal:底层用len<<3所以aaa数组的长度要很大才能跑起来

hutool URL工具

TestURL

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.URLUtil;import org.junit.Test;
  3. public class TestURL extends myHutool {
  4. @Test
  5. @Comment("URLUtil使用举例")
  6. public void test1(){
  7. String url1 = "hutool.cn";
  8. String url2 = "https://apidoc.gitee.com/dromara/hutool/";
  9. String urla = URLUtil.formatUrl(url1);
  10. String urlb = URLUtil.encode(url2);
  11. String urlc = URLUtil.decode(urlb);
  12. String urld = URLUtil.getPath(url2);
  13. p1("原数据",url1,"格式化之后",urla);
  14. p1("原数据",url2,"编码数据",urlb);
  15. p1("编码数据",urlb,"解码数据",urlc);
  16. p1("原数据",url2,"对应路径",urld);
  17. }
  18. }

hutool Base32-64工具

TestIdBase32_64

  1. package cn.hutool.test;
  2. import cn.hutool.core.codec.Base32;import cn.hutool.core.codec.Base64;import org.junit.Test;
  3. public class TestIdBase32_64 extends myHutool {
  4. @Test
  5. @Comment("Base32_64转换")
  6. public void test1(){
  7. String charset = "utf-8";
  8. String content = "hutool.cn - java教程";
  9. p3("原字符串",content);
  10. String code32 = Base32.encode(content,charset);
  11. content = Base32.decodeStr(code32,charset);
  12. p3("32位编码后",code32);
  13. p3("32位解码",content);
  14. String code64 = Base64.encode(content,charset);
  15. content = Base64.decodeStr(code64,charset);
  16. p3("64位编码后",code64);
  17. p3("64位解码",content);
  18. }
  19. }

hutool Unicode工具

TestUnicode

  1. package cn.hutool.test;
  2. import cn.hutool.core.text.UnicodeUtil;import org.junit.Test;
  3. public class TestUnicode extends myHutool {
  4. @Test
  5. @Comment("unicode转换")
  6. public void test1(){
  7. String charset = "utf-8";
  8. String content = "hutool.cn - java教程";
  9. p3("原字符串",content);
  10. String unicode = UnicodeUtil.toUnicode(content);
  11. content = UnicodeUtil.toString(unicode);
  12. p3("获取unicode",unicode);
  13. p3("转回原字符串",content);
  14. }
  15. }

三、常用类辅助工具

hutool 转换工具

pom.xml
因为使用了junit,所以pom里加上junit的依赖

  1. <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>cn.hutool</groupId>
  6. <artifactId>hutool</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>hutool</name>
  9. <description>hutool</description>
  10. <dependencies>
  11. <dependency>
  12. <groupId>cn.hutool</groupId>
  13. <artifactId>hutool-all</artifactId>
  14. <version>4.3.1</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>asm</groupId>
  18. <artifactId>asm-all</artifactId>
  19. <version>3.3.1</version>
  20. <scope>test</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>junit</groupId>
  24. <artifactId>junit</artifactId>
  25. <version>4.12</version>
  26. </dependency>
  27. </dependencies>
  28. </project>

TestConverter

  1. package cn.hutool.test;
  2. import cn.hutool.core.convert.Convert;import cn.hutool.core.util.CharsetUtil;import org.junit.Test;
  3. import java.util.List;
  4. public class TestConverter extends myHutool {
  5. @Test
  6. @Comment("转换为字符串")
  7. public void test1(){
  8. int a = 1;
  9. String aStr = Convert.toStr(a);
  10. int b[] = {1,2,3,4,5};
  11. String bStr = Convert.toStr(b);
  12. Object c = null;
  13. String cStr = Convert.toStr(c,"空字符串(默认值)");
  14. p1("整数",a,"字符串",aStr);
  15. p1("long数组",b,"字符串",bStr);
  16. p1("空对象",c,"字符串",cStr);
  17. }
  18. @Test
  19. @Comment("数组类型互相转化")
  20. public void test2(){
  21. String[] a = {"1","2","3","4"};
  22. Integer[] b = Convert.toIntArray(a);
  23. p1("字符串数组",Convert.toStr(a),"Integer数组",Convert.toStr(b));
  24. }
  25. @Test
  26. @Comment("数组和集合互换")
  27. public void test3(){
  28. String[] a = {"1","2","3","4"};
  29. List<?> l = Convert.toList(a);
  30. String[] b = Convert.toStrArray(l);
  31. p1("字符串数组",a,"集合",l);
  32. p1("集合",l,"字符串数组",b);
  33. }
  34. @Test
  35. @Comment("半角全角互相转换")
  36. public void test4(){
  37. String a = "123456789";
  38. String b = Convert.toSBC(a);
  39. String c = Convert.toDBC(b);
  40. p1("半角",a,"全角",b);
  41. p1("全角",b,"半角",c);
  42. }
  43. @Test
  44. @Comment("Unicode和字符串转换")
  45. public void test5(){
  46. String a = "HuTool的java教程";
  47. String unicode = Convert.strToUnicode(a);
  48. String b = Convert.unicodeToStr(unicode);
  49. p1("字符串",a,"unicode",unicode);
  50. p1("unicode",unicode,"字符串",b);
  51. }
  52. @Test
  53. @Comment("不同编码之间的转换")
  54. public void test6(){
  55. String a = "HuTool的java教程";
  56. //转换后result为乱码
  57. String b = Convert.convertCharset(a, CharsetUtil.UTF_8,CharsetUtil.ISO_8859_1);
  58. String c = Convert.convertCharset(b,CharsetUtil.ISO_8859_1,"UTF-8");
  59. p1("UTF-8",a,"ISO-8859-1",b);
  60. p1("ISO-8859-1",b,"UTF-8",c);
  61. }
  62. @Test
  63. @Comment("数字转换为金额")
  64. public void test7(){
  65. double a = 1234567123456.12;
  66. String b = Convert.digitToChinese(a);
  67. p1("数字",a,"钞票金额",b);
  68. }
  69. @Test
  70. @Comment("原始类和包装类转换")
  71. public void test8(){
  72. Class<?> wrapClass = Integer.class;
  73. Class<?> unWraped = Convert.unWrap(wrapClass);
  74. Class<?> primitveClass = long.class;
  75. Class<?> wraped = Convert.wrap(primitveClass);
  76. p1("包装类型",wrapClass,"原始类型",unWraped);
  77. p1("原始类型",unWraped,"wraped",wraped);
  78. }
  79. }

hutool 日期工具

TestDate

  1. package cn.hutool.test;
  2. import cn.hutool.core.date.*;import cn.hutool.core.date.BetweenFormater.Level;import org.junit.Test;
  3. import java.util.Date;
  4. public class TestDate extends myHutool {
  5. @Test
  6. @Comment("字符串转日期")
  7. public void test1(){
  8. printDefaultFormat();
  9. Date date;
  10. String str1 = "12:12:12";
  11. date = DateUtil.parse(str1);
  12. p1("字符串",str1,"日期格式",date);
  13. String str2 = "2021-04-11";
  14. date = DateUtil.parse(str2);
  15. p1("字符串",str2,"日期格式",date);
  16. String str3 = "2021-04-11 12:12";
  17. date = DateUtil.parse(str3);
  18. p1("字符串",str3,"日期格式",date);
  19. String str4 = "2021-04-11 12:12:12";
  20. date = DateUtil.parse(str4);
  21. p1("字符串",str4,"日期格式",date);
  22. }
  23. @Test
  24. @Comment("日期转字符串")
  25. public void test2(){
  26. Date date = new Date();
  27. //结果:"2021/04/11"
  28. String format = DateUtil.format(date, "yyyy/MM/dd");
  29. p1("日期格式",date,"自定义格式的字符串",format);
  30. //常用格式的格式化,结果:"2021-04-11"
  31. String formatDate = DateUtil.formatDate(date);
  32. p1("日期格式",date,"只是日期格式",formatDate);
  33. //结果:"2021-04-11 17:32:38"
  34. String formatDateTime = DateUtil.formatDateTime(date);
  35. p1("日期格式",date,"日期和时间格式",formatDateTime);
  36. //结果:"17:32:38"
  37. String formatTime = DateUtil.formatTime(date);
  38. p1("日期格式",date,"只是时间格式",formatTime);
  39. }
  40. @Test
  41. @Comment("获取部分信息")
  42. public void test3(){
  43. Date date = new Date();
  44. //获得年的部分
  45. int year = DateUtil.year(date);
  46. //获得月份,从0开始计数
  47. int month = DateUtil.month(date);
  48. //获得月份枚举
  49. Month months = DateUtil.monthEnum(date);
  50. p2("当前日期",DateUtil.formatDateTime(date),"年份",year);
  51. p2("当前日期",DateUtil.formatDateTime(date),"月份",month);
  52. p2("当前日期",DateUtil.formatDateTime(date),"月份枚举信息",months);
  53. }
  54. @Test
  55. @Comment("开始时间和结束时间")
  56. public void test4(){
  57. Date date = new Date();
  58. //一天的开始
  59. DateTime beginOfDay = DateUtil.beginOfDay(date);
  60. //一天的结束
  61. DateTime endOfDay = DateUtil.endOfDay(date);
  62. p2("当前日期",DateUtil.formatDateTime(date),"开始时间",beginOfDay);
  63. p2("当前日期",DateUtil.formatDateTime(date),"结束时间",endOfDay);
  64. c("这个在查询数据库时,根据日期查一个范围内的数据就很有用");
  65. }
  66. @Test
  67. @Comment("日期时间偏移")
  68. public void test5(){
  69. Date date = new Date();
  70. DateTime d1 = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
  71. DateTime d2 = DateUtil.offsetDay(date, 3);
  72. DateTime d3 = DateUtil.offsetHour(date, -3);
  73. p2("当前日期",DateUtil.formatDateTime(date),"两天之后的日期",d1);
  74. p2("当前日期",DateUtil.formatDateTime(date),"三天之后的日期",d2);
  75. p2("当前日期",DateUtil.formatDateTime(date),"三小时之前的日期",d3);
  76. }
  77. @Test
  78. @Comment("偏移简易用法")
  79. public void test6(){
  80. Date date = new Date();
  81. Date d1 = DateUtil.yesterday();
  82. Date d2 = DateUtil.tomorrow();
  83. Date d3 = DateUtil.lastWeek();
  84. Date d4 = DateUtil.nextWeek();
  85. Date d5 = DateUtil.lastMonth();
  86. Date d6 = DateUtil.nextMonth();
  87. p2("当前日期",DateUtil.formatDateTime(date),"昨天",d1);
  88. p2("当前日期",DateUtil.formatDateTime(date),"明天",d2);
  89. p2("当前日期",DateUtil.formatDateTime(date),"上一周",d3);
  90. p2("当前日期",DateUtil.formatDateTime(date),"下一周",d4);
  91. p2("当前日期",DateUtil.formatDateTime(date),"上个月",d5);
  92. p2("当前日期",DateUtil.formatDateTime(date),"下个月",d6);
  93. }
  94. @Test
  95. @Comment("日期时间差")
  96. public void test7(){
  97. Date date1 = DateUtil.parse("2021-04-11 17:54:28");
  98. Date date2 = DateUtil.parse("2021-03-11 17:54:28");
  99. long b1 = DateUtil.between(date1, date2, DateUnit.MS);
  100. long b2 = DateUtil.between(date1, date2, DateUnit.SECOND);
  101. long b3 = DateUtil.between(date1, date2, DateUnit.MINUTE);
  102. long b4 = DateUtil.between(date1, date2, DateUnit.HOUR);
  103. long b5 = DateUtil.between(date1, date2, DateUnit.DAY);
  104. long b6 = DateUtil.between(date1, date2, DateUnit.WEEK);
  105. p2("当前如下两个日期",date1 + " ~ " + date2, "相差毫秒",b1);
  106. p2("当前如下两个日期",date1 + " ~ " + date2, "相差秒",b2);
  107. p2("当前如下两个日期",date1 + " ~ " + date2, "相差分",b3);
  108. p2("当前如下两个日期",date1 + " ~ " + date2, "相差小时",b4);
  109. p2("当前如下两个日期",date1 + " ~ " + date2, "相差天",b5);
  110. p2("当前如下两个日期",date1 + " ~ " + date2, "相差星期",b6);
  111. }
  112. @Test
  113. @Comment("格式时间差")
  114. public void test8(){
  115. long between = System.currentTimeMillis();
  116. String s1 = DateUtil.formatBetween(between, Level.MILLSECOND);
  117. String s2 = DateUtil.formatBetween(between,Level.SECOND);
  118. String s3 = DateUtil.formatBetween(between,Level.MINUTE);
  119. String s4 = DateUtil.formatBetween(between,Level.HOUR);
  120. String s5 = DateUtil.formatBetween(between,Level.DAY);
  121. p2("毫秒数",between,"对应时间,精度到毫秒",s1);
  122. p2("毫秒数",between,"对应时间,精度到秒",s2);
  123. p2("毫秒数",between,"对应时间,精度到秒分钟",s3);
  124. p2("毫秒数",between,"对应时间,精度到秒小时",s4);
  125. p2("毫秒数",between,"对应时间,精度到秒天",s5);
  126. }
  127. @Test
  128. @Comment("性能统计")
  129. public void test9(){
  130. int loopcount = 100;
  131. TimeInterval timer = DateUtil.timer();
  132. forloop(loopcount);
  133. long interval1 = timer.interval();
  134. forloop(loopcount);
  135. long interval2 = timer.intervalRestart();
  136. forloop(loopcount);
  137. long interval3 = timer.interval();
  138. p3("性能统计,总共花费了 (毫秒数)",interval1);
  139. p3("性能统计,总共花费了 (毫秒数),并重置",interval2);
  140. p3("性能统计,总共花费了 (毫秒数)",interval3);
  141. }
  142. @Test
  143. @Comment("其他")
  144. public void test10(){
  145. String birthDay = "1949-10-01";
  146. int age = DateUtil.ageOfNow(birthDay);
  147. int year = 2021;
  148. boolean isleap = DateUtil.isLeapYear(year);
  149. String now = DateUtil.now();
  150. String today = DateUtil.today();
  151. p2("生日",birthDay,"年龄",age);
  152. p2("年份",year,"是否闰年",isleap);
  153. p3("现在",now);
  154. p3("今天",today);
  155. }
  156. private void forloop(int total) {
  157. for (int i = 0; i < total; i++) {
  158. try {
  159. Thread.sleep(1);
  160. } catch (InterruptedException e) {
  161. e.printStackTrace();
  162. }
  163. }
  164. }
  165. public void printDefaultFormat() {
  166. System.out.println("DateUtil默认会对如下格式进行识别:");
  167. System.out.println();
  168. System.out.println("\tyyyy-MM-dd HH:mm:ss");
  169. System.out.println("\tyyyy/MM/dd HH:mm:ss");
  170. System.out.println("\tyyyy.MM.dd HH:mm:ss");
  171. System.out.println("\tyyyy年MM月dd日 HH时mm分ss秒");
  172. System.out.println("\tyyyy-MM-dd");
  173. System.out.println("\tyyyy/MM/dd");
  174. System.out.println("\tyyyy.MM.dd");
  175. System.out.println("\tHH:mm:ss");
  176. System.out.println("\tHH时mm分ss秒");
  177. System.out.println("\tyyyy-MM-dd HH:mm");
  178. System.out.println("\tyyyy-MM-dd HH:mm:ss.SSS");
  179. System.out.println("\tyyyyMMddHHmmss");
  180. System.out.println("\tyyyyMMddHHmmssSSS");
  181. System.out.println("\tyyyyMMdd");
  182. System.out.println();
  183. }
  184. }

hutool 字符串工具

21.1 StrUtil

StrUtil 功能很强大,里面提供了很多很多字符串相关的操作。

21.2 与空判断相关的
  1. public static boolean isBlank(CharSequence str)
  2. public static boolean isBlankIfStr(Object obj)
  3. public static boolean isNotBlank(CharSequence str)
  4. public static boolean hasBlank(CharSequence... strs)
  5. public static boolean isAllBlank(CharSequence... strs)
  6. public static boolean isEmpty(CharSequence str)
  7. public static boolean isEmptyIfStr(Object obj)
  8. public static boolean isNotEmpty(CharSequence str)
  9. public static String nullToEmpty(CharSequence str)
  10. public static String nullToDefault(CharSequence str, String defaultStr)
  11. public static String emptyToDefault(CharSequence str, String defaultStr)
  12. public static String blankToDefault(CharSequence str, String defaultStr)
  13. public static String emptyToNull(CharSequence str)
  14. public static boolean hasEmpty(CharSequence... strs)
  15. public static boolean isAllEmpty(CharSequence... strs)
  16. public static boolean isNullOrUndefined(CharSequence str)
  17. public static boolean isEmptyOrUndefined(CharSequence str)
  18. public static boolean isBlankOrUndefined(CharSequence str)
  19. public static String cleanBlank(CharSequence str)

21.3 头尾处理
  1. public static String trim(CharSequence str)
  2. public static void trim(String[] strs)
  3. public static String trimToEmpty(CharSequence str)
  4. public static String trimToNull(CharSequence str)
  5. public static String trimStart(CharSequence str)
  6. public static String trimEnd(CharSequence str)
  7. public static String trim(CharSequence str, int mode)
  8. public static String strip(CharSequence str, CharSequence prefixOrSuffix)
  9. public static String strip(CharSequence str, CharSequence prefix, CharSequence suffix)
  10. public static String stripIgnoreCase(CharSequence str, CharSequence prefixOrSuffix)
  11. public static String stripIgnoreCase(CharSequence str, CharSequence prefix, CharSequence suffix)
  12. public static String addPrefixIfNot(CharSequence str, CharSequence prefix)
  13. public static String addSuffixIfNot(CharSequence str, CharSequence suffix)
  14. public static boolean isSurround(CharSequence str, CharSequence prefix, CharSequence suffix)
  15. public static boolean isSurround(CharSequence str, char prefix, char suffix)

21.4 包含与否
  1. public static boolean startWith(CharSequence str, char c)
  2. public static boolean startWith(CharSequence str, CharSequence prefix, boolean isIgnoreCase)
  3. public static boolean startWith(CharSequence str, CharSequence prefix)
  4. public static boolean startWithIgnoreCase(CharSequence str, CharSequence prefix)
  5. public static boolean startWithAny(CharSequence str, CharSequence... prefixes)
  6. public static boolean endWith(CharSequence str, char c)
  7. public static boolean endWith(CharSequence str, CharSequence suffix, boolean isIgnoreCase)
  8. public static boolean endWith(CharSequence str, CharSequence suffix)
  9. public static boolean endWithIgnoreCase(CharSequence str, CharSequence suffix)
  10. public static boolean endWithAny(CharSequence str, CharSequence... suffixes)
  11. public static boolean contains(CharSequence str, char searchChar)
  12. public static boolean containsAny(CharSequence str, CharSequence... testStrs)
  13. public static boolean containsAny(CharSequence str, char... testChars)
  14. public static boolean containsBlank(CharSequence str)
  15. public static String getContainsStr(CharSequence str, CharSequence... testStrs)
  16. public static boolean containsIgnoreCase(CharSequence str, CharSequence testStr)
  17. public static boolean containsAnyIgnoreCase(CharSequence str, CharSequence... testStrs)
  18. public static String getContainsStrIgnoreCase(CharSequence str, CharSequence... testStrs)

21.5 setter gettter 处理
  1. public static String getGeneralField(CharSequence getOrSetMethodName)
  2. public static String genSetter(CharSequence fieldName)
  3. public static String genGetter(CharSequence fieldName)

21.6 删除
  1. public static String removeAll(CharSequence str, CharSequence strToRemove)
  2. public static String removeAll(CharSequence str, char... chars)
  3. public static String removeAllLineBreaks(CharSequence str)
  4. public static String removePreAndLowerFirst(CharSequence str, int preLength)
  5. public static String removePreAndLowerFirst(CharSequence str, CharSequence prefix)
  6. public static String removePrefix(CharSequence str, CharSequence prefix)
  7. public static String removePrefixIgnoreCase(CharSequence str, CharSequence prefix)
  8. public static String removeSuffix(CharSequence str, CharSequence suffix)
  9. public static String removeSufAndLowerFirst(CharSequence str, CharSequence suffix)
  10. public static String removeSuffixIgnoreCase(CharSequence str, CharSequence suffix)

21.7 大小写
  1. public static String upperFirstAndAddPre(CharSequence str, String preString)
  2. public static String upperFirst(CharSequence str)
  3. public static String lowerFirst(CharSequence str)
  4. public static boolean isUpperCase(CharSequence str)
  5. public static boolean isLowerCase(CharSequence str)

21.8 分割
  1. public static String[] splitToArray(CharSequence str, char separator)
  2. public static long[] splitToLong(CharSequence str, char separator)
  3. public static long[] splitToLong(CharSequence str, CharSequence separator)
  4. public static int[] splitToInt(CharSequence str, char separator)
  5. public static int[] splitToInt(CharSequence str, CharSequence separator)
  6. public static List<String> split(CharSequence str, char separator)
  7. public static String[] splitToArray(CharSequence str, char separator, int limit)
  8. public static List<String> split(CharSequence str, char separator, int limit)
  9. public static List<String> splitTrim(CharSequence str, char separator)
  10. public static List<String> splitTrim(CharSequence str, CharSequence separator)
  11. public static List<String> splitTrim(CharSequence str, char separator, int limit)
  12. public static List<String> splitTrim(CharSequence str, CharSequence separator, int limit)
  13. public static List<String> split(CharSequence str, char separator, boolean isTrim, boolean ignoreEmpty)
  14. public static List<String> split(CharSequence str, char separator, int limit, boolean isTrim, boolean ignoreEmpty)
  15. public static List<String> split(CharSequence str, CharSequence separator, int limit, boolean isTrim, boolean ignoreEmpty)
  16. public static String[] split(CharSequence str, CharSequence separator)
  17. public static String[] split(CharSequence str, int len)
  18. public static String[] cut(CharSequence str, int partLength)

21.9 截取
  1. public static String sub(CharSequence str, int fromIndex, int toIndex)
  2. public static String subPreGbk(CharSequence str, int len, CharSequence suffix)
  3. public static String maxLength(CharSequence string, int length)
  4. public static String subPre(CharSequence string, int toIndex)
  5. public static String subSuf(CharSequence string, int fromIndex)
  6. public static String subSufByLength(CharSequence string, int length)
  7. public static String subWithLength(String input, int fromIndex, int length)
  8. public static String subBefore(CharSequence string, CharSequence separator, boolean isLastSeparator)
  9. public static String subBefore(CharSequence string, char separator, boolean isLastSeparator)
  10. public static String subAfter(CharSequence string, CharSequence separator, boolean isLastSeparator)
  11. public static String subAfter(CharSequence string, char separator, boolean isLastSeparator)
  12. public static String subBetween(CharSequence str, CharSequence before, CharSequence after)
  13. public static String subBetween(CharSequence str, CharSequence beforeAndAfter)

21.10 创建字符串
  1. public static String repeat(char c, int count)
  2. public static String repeat(CharSequence str, int count)
  3. public static String repeatAndJoin(CharSequence str, int count, CharSequence conjunction)

21.11 是否相等
  1. public static boolean equals(CharSequence str1, CharSequence str2)
  2. public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2)
  3. public static boolean equals(CharSequence str1, CharSequence str2, boolean ignoreCase)
  4. public static boolean isSubEquals(CharSequence str1, int start1, CharSequence str2, int start2, int length, boolean ignoreCase)
  5. public static boolean isAllCharMatch(CharSequence value, Matcher<Character> matcher)
  6. public static boolean equalsCharAt(CharSequence str, int position, char c)

21.12 格式化
  1. public static String format(CharSequence template, Object... params)
  2. public static String indexedFormat(CharSequence pattern, Object... arguments)
  3. public static String format(CharSequence template, Map<?, ?> map)

21.13 获取字节
  1. public static byte[] utf8Bytes(CharSequence str)
  2. public static byte[] bytes(CharSequence str)
  3. public static byte[] bytes(CharSequence str, String charset)
  4. public static byte[] bytes(CharSequence str, Charset charset)

21.14 转换为字符串
  1. public static String utf8Str(Object obj)
  2. public static String str(Object obj, String charsetName)
  3. public static String str(Object obj, Charset charset)
  4. public static String str(byte[] bytes, String charset)
  5. public static String str(byte[] data, Charset charset)
  6. public static String str(Byte[] bytes, String charset)
  7. public static String str(Byte[] data, Charset charset)
  8. public static String str(ByteBuffer data, String charset)
  9. public static String str(ByteBuffer data, Charset charset)
  10. public static String str(CharSequence cs)
  11. public static String toString(Object obj)
  12. public static String join(CharSequence conjunction, Object... objs)

21.15 格式转换
  1. public static String toUnderlineCase(CharSequence str)
  2. public static String toSymbolCase(CharSequence str, char symbol)
  3. public static String toCamelCase(CharSequence name)

21.16 包裹
  1. public static String wrap(CharSequence str, CharSequence prefixAndSuffix)
  2. public static String wrap(CharSequence str, CharSequence prefix, CharSequence suffix)
  3. public static String[] wrapAll(CharSequence prefixAndSuffix, CharSequence... strs)
  4. public static String[] wrapAll(CharSequence prefix, CharSequence suffix, CharSequence... strs)
  5. public static String wrapIfMissing(CharSequence str, CharSequence prefix, CharSequence suffix)
  6. public static String[] wrapAllIfMissing(CharSequence prefixAndSuffix, CharSequence... strs)
  7. public static String[] wrapAllIfMissing(CharSequence prefix, CharSequence suffix, CharSequence... strs)
  8. public static String unWrap(CharSequence str, String prefix, String suffix)
  9. public static String unWrap(CharSequence str, char prefix, char suffix)
  10. public static String unWrap(CharSequence str, char prefixAndSuffix)
  11. ublic static boolean isWrap(CharSequence str, String prefix, String suffix)
  12. public static boolean isWrap(CharSequence str, String wrapper)
  13. public static boolean isWrap(CharSequence str, char wrapper)
  14. public static boolean isWrap(CharSequence str, char prefixChar, char suffixChar)

21.17 填充
  1. public static String padPre(CharSequence str, int minLength, char padChar)
  2. public static String padEnd(CharSequence str, int minLength, char padChar)
  3. public static StringBuilder builder()public static String fillBefore(String str, char filledChar, int len)
  4. public static String fillAfter(String str, char filledChar, int len)
  5. public static String fill(String str, char filledChar, int len, boolean isPre)

21.18 获取其他对象
  1. public static StrBuilder strBuilder()
  2. public static StringBuilder builder(int capacity)
  3. public static StrBuilder strBuilder(int capacity)
  4. public static StringBuilder builder(CharSequence... strs)
  5. public static StrBuilder strBuilder(CharSequence... strs)
  6. public static StringReader getReader(CharSequence str)
  7. public static StringWriter getWriter()

21.19 出现次数
  1. public static int count(CharSequence content, CharSequence strForSearch)
  2. public static int count(CharSequence content, char charForSearch)

21.20 摘要和隐藏
  1. public static String brief(CharSequence str, int maxLength)
  2. public static String hide(CharSequence str, int startInclude, int endExclude)

21.21 比较
  1. public static int compare(final CharSequence str1, final CharSequence str2, final boolean nullIsLess)
  2. public static int compareIgnoreCase(CharSequence str1, CharSequence str2, boolean nullIsLess)
  3. public static int compareVersion(CharSequence version1, CharSequence version2)

21.22 获取索引位置
  1. public static int indexOf(final CharSequence str, char searchChar)
  2. public static int indexOf(final CharSequence str, char searchChar, int start)
  3. public static int indexOf(final CharSequence str, char searchChar, int start, int end)
  4. public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr)
  5. public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex)
  6. public static int indexOf(final CharSequence str, CharSequence searchStr, int fromIndex, boolean ignoreCase)
  7. public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr)
  8. public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex)
  9. public static int lastIndexOf(final CharSequence str, final CharSequence searchStr, int fromIndex, boolean ignoreCase)
  10. public static int ordinalIndexOf(String str, String searchStr, int ordinal)

21.23 追加
  1. public static String appendIfMissing(final CharSequence str, final CharSequence suffix, final CharSequence... suffixes)
  2. public static String appendIfMissingIgnoreCase(final CharSequence str, final CharSequence suffix, final CharSequence... suffixes)
  3. public static String appendIfMissing(final CharSequence str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes)
  4. public static String prependIfMissing(final CharSequence str, final CharSequence prefix, final CharSequence... prefixes)
  5. public static String prependIfMissingIgnoreCase(final CharSequence str, final CharSequence prefix, final CharSequence... prefixes)
  6. public static String prependIfMissing(final CharSequence str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes)

21.24 替换
  1. public static String replaceIgnoreCase(CharSequence str, CharSequence searchStr, CharSequence replacement)
  2. public static String replace(CharSequence str, CharSequence searchStr, CharSequence replacement)
  3. public static String replace(CharSequence str, CharSequence searchStr, CharSequence replacement, boolean ignoreCase)
  4. public static String replace(CharSequence str, int fromIndex, CharSequence searchStr, CharSequence replacement, boolean ignoreCase)
  5. public static String replace(CharSequence str, int startInclude, int endExclude, char replacedChar)
  6. public static String replace(CharSequence str, Pattern pattern, Func1<java.util.regex.Matcher, String> replaceFun)
  7. public static String replace(CharSequence str, String regex, Func1<java.util.regex.Matcher, String> replaceFun)
  8. public static String replaceChars(CharSequence str, String chars, CharSequence replacedStr)
  9. public static String replaceChars(CharSequence str, char[] chars, CharSequence replacedStr)

21.25 相似度
  1. public static double similar(String str1, String str2)
  2. public static String similar(String str1, String str2, int scale)

21.26 其他
  1. 总长度 public static int totalLength(CharSequence... strs)
  2. 移动 public static String move(CharSequence str, int startInclude, int endExclude, int moveLength)
  3. uuid public static String uuid()
  4. 连接 public static String concat(boolean isNullToEmpty, CharSequence... strs)
  5. 反转 public static String reverse(String str)

hutool 数字工具

TestNumber

  1. package cn.hutool.test;
  2. import cn.hutool.core.convert.Convert;import cn.hutool.core.util.NumberUtil;import cn.hutool.core.util.StrUtil;import org.junit.Test;
  3. public class TestNumber extends myHutool {
  4. @Test
  5. @Comment("精确计算")
  6. public void test1() {
  7. double result1 = (1.2 - 0.4);
  8. p3("浮点数计算 1.2 - 0.4 无法得到精确结果",result1);
  9. double result2 = NumberUtil.sub(1.2, 0.4);
  10. p3("浮点数计算 NumberUtil.sub(1.2,0.4) 就能得到精确结果",result2);
  11. }
  12. @Test
  13. @Comment("四舍五入")
  14. public void test2() {
  15. double a = 100.123;
  16. double b = 100.125;
  17. double result1 = NumberUtil.round(a,2).doubleValue();
  18. double result2 = NumberUtil.round(b,2).doubleValue();
  19. p1("浮点数",a,"四舍五入之后",result1);
  20. p1("浮点数",b,"四舍五入之后",result2);
  21. }
  22. @Test
  23. @Comment("数字格式化")
  24. public void test3(){
  25. // 0 -> 取一位整数
  26. // 0.00 -> 取一位整数和两位小数
  27. // 00.000 -> 取两位整数和三位小数
  28. // # -> 取所有整数部分
  29. // #.##% -> 以百分比方式计数,并取两位小数
  30. // #.#####E0 -> 显示为科学计数法,并取五位小数
  31. // ,### -> 每三位以逗号进行分隔,例如:299,792,458
  32. // 光速大小为每秒,###米 -> 将格式嵌入文本
  33. p3("对π进行格式化,π的值是",Math.PI);
  34. double pi= Math.PI;
  35. String format = null;
  36. String str = null;
  37. format= "0";
  38. str = NumberUtil.decimalFormat(format,pi);
  39. p2("格式",format,"格式化后得到", str);
  40. format= "0.00";
  41. str = NumberUtil.decimalFormat(format,pi);
  42. p2("格式",format,"格式化后得到", str);
  43. format= "00.000";
  44. str = NumberUtil.decimalFormat(format,pi);
  45. p2("格式",format,"格式化后得到", str);
  46. format= "#";
  47. str = NumberUtil.decimalFormat(format,pi);
  48. p2("格式",format,"格式化后得到", str);
  49. format= "#.##";
  50. str = NumberUtil.decimalFormat(format,pi);
  51. p2("格式",format,"格式化后得到", str);
  52. format= "#.##%";
  53. str = NumberUtil.decimalFormat(format,pi);
  54. p2("格式",format,"格式化后得到", str);
  55. format= "#.####E0";
  56. str = NumberUtil.decimalFormat(format,pi);
  57. p2("格式",format,"格式化后得到", str);
  58. format= ",###";
  59. str = NumberUtil.decimalFormat(format,pi*10000);
  60. p2("格式",format,"x1000 再格式化后得到", str);
  61. format= ",####";
  62. str = NumberUtil.decimalFormat(format,pi*10000);
  63. p2("格式",format,"x1000 再格式化后得到", str);
  64. format= "π的大小是#.##########";
  65. str = NumberUtil.decimalFormat(format,pi);
  66. p2("格式",format,"格式化后得到", str);
  67. }
  68. @Test
  69. @Comment("数字判断")
  70. public void test4() {
  71. String s1 = "3.1415926";
  72. int n = 11;
  73. p2("字符串",s1,"是否数字",NumberUtil.isNumber(s1));
  74. p2("字符串",s1,"是否整数(这个有问题)",NumberUtil.isInteger(s1));
  75. p2("字符串",s1,"是否浮点数",NumberUtil.isDouble(s1));
  76. p2("整数",n,"是否质数",NumberUtil.isPrimes(n));
  77. }
  78. @Test
  79. @Comment("随机数")
  80. public void test5() {
  81. int[] random = NumberUtil.generateRandomNumber(1, 1000, 10);
  82. p3("最小是1,最大是1000,总长度是10的不重复随机数组", Convert.toStr(random));
  83. }
  84. @Test
  85. @Comment("整数列表")
  86. public void test6() {
  87. int[] numbers = NumberUtil.range(0, 100, 9);
  88. p3("最小是0,最大是100,步长是9的数组",Convert.toStr(numbers));
  89. }
  90. @Test
  91. @Comment("其他相关")
  92. public void test7() {
  93. p3("计算3的阶乘",NumberUtil.factorial(3));
  94. p3("计算9的平方根",NumberUtil.sqrt(9));
  95. p3("计算6和9的最大公约数",NumberUtil.divisor(9,6));
  96. p3("计算9和6的最小公倍数",NumberUtil.multiple(9,6));
  97. p3("获得数字9对应的二进制字符串",NumberUtil.getBinaryStr(9));
  98. p3("获得123456789对应金额",NumberUtil.decimalFormatMoney(123456789));
  99. }
  100. }

问题解决:
数字判断
判断不了整数的原因是hutool版本太低将版本升级到4.4.0即可,版本太高的话会有很多过时的方法导致报错
换成4.4.0版本后会有 padEnd报红的错误,原因是该方法以删除,换成 padAfter即可

hutool 数组工具

TestArray

  1. package cn.hutool.test;
  2. import cn.hutool.core.convert.Convert;import cn.hutool.core.lang.Filter;import cn.hutool.core.util.ArrayUtil;import org.junit.Test;
  3. import java.util.Map;
  4. public class TestArray extends myHutool {
  5. @Test
  6. @Comment("为空判断")
  7. public void test1() {
  8. int[] a = null;
  9. int[] b = new int[5];
  10. int[] c = new int[]{10,11,12};
  11. p1("数组", Convert.toStr(a),"是否为空", ArrayUtil.isEmpty(a));
  12. p1("数组", Convert.toStr(b),"是否为空", ArrayUtil.isEmpty(b));
  13. p1("数组", Convert.toStr(c),"是否为空", ArrayUtil.isEmpty(c));
  14. }
  15. @Test
  16. @Comment("调整数组大小")
  17. public void test2() {
  18. Integer[] a = new Integer[]{10, 11, 12};
  19. Integer[] b = ArrayUtil.resize(a, 5);
  20. p3("调整大小前的数组",Convert.toStr(a));
  21. p3("调整大小后的数组",Convert.toStr(b));
  22. }
  23. @Test
  24. @Comment("合并数组")
  25. public void test3() {
  26. Integer[] a = {1,2,3};
  27. Integer[] b = {10,11,12};
  28. Integer[] c = ArrayUtil.addAll(a,b);
  29. p2("合并前的两个数组 ",Convert.toStr(a)+" , "+Convert.toStr(b),"合并后的数组是",Convert.toStr(c));
  30. }
  31. @Test
  32. @Comment("克隆")
  33. public void test4() {
  34. Integer[] a = {1,2,3};
  35. Integer[] b = ArrayUtil.clone(a);
  36. p2("原数组",Convert.toStr(a),"克隆的数组",Convert.toStr(b));
  37. }
  38. @Test
  39. @Comment("生成有序数组")
  40. public void test5() {
  41. p3("生成开始是0,结束是100,步长是9的有序数组",Convert.toStr(ArrayUtil.range(0,100,9)));
  42. }
  43. @Test
  44. @Comment("过滤")
  45. public void test6() {
  46. Integer[] a = {1,2,3,4,5,6,7,8,9};
  47. Integer[] b = ArrayUtil.filter(a, new Filter<Integer>() {
  48. @Override
  49. public boolean accept(Integer integer) {
  50. if (0==integer%3)
  51. return true;
  52. return false;
  53. }
  54. });
  55. p2("原数组",Convert.toStr(a),"3的倍数过滤之后",Convert.toStr(b));
  56. }
  57. @Test
  58. @Comment("转换为map")
  59. public void test7() {
  60. Integer[] a = {1,2,3};
  61. String[] c = {"a","b","c"};
  62. Map<Integer, String> m = ArrayUtil.zip(a, c);
  63. p2("两个数组",Convert.toStr(a)+" , "+Convert.toStr(c),"转换为 Map ",m);
  64. }
  65. @Test
  66. @Comment("是否包含某元素")
  67. public void test8() {
  68. Integer[] a = {1,2,3};
  69. p1("数组",Convert.toStr(a),"是否包含元素3",ArrayUtil.contains(a,3));
  70. }
  71. @Test
  72. @Comment("装箱拆箱")
  73. public void test9() {
  74. int[] a = {1,2,3};
  75. Integer[] b = ArrayUtil.wrap(a);
  76. int[] c = ArrayUtil.unWrap(b);
  77. p3("数组基于类型的装箱拆箱","ArrayUtil.wrap | ArrayUtil.unWrap");
  78. }
  79. @Test
  80. @Comment("转换为字符串")
  81. public void testa() {
  82. int[] a = {1,2,3};
  83. p3("数组转换为默认字符串",ArrayUtil.toString(a));
  84. p3("数组转换为自定义分隔符的字符串",ArrayUtil.join(a,"-"));
  85. }
  86. @Test
  87. @Comment("拆分")
  88. public void testb() {
  89. byte[] a = {1,2,3,4,5,6,7,8,9};
  90. byte[][] b = ArrayUtil.split(a,2);
  91. p3("数组被拆分2为长度的等份",Convert.toStr(a));
  92. for (byte[] bs : b){
  93. p3("拆分后的数组:",Convert.toStr(bs));
  94. }
  95. }
  96. }

hutool 随机工具

TestRandom

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.RandomUtil;import org.junit.Test;
  3. import java.util.ArrayList;
  4. public class TestRandom extends myHutool {
  5. @Test
  6. @Comment("各种各样的随机数")
  7. public void test1() {
  8. ArrayList<Object> ls = new ArrayList<>();
  9. ls.add(1);
  10. ls.add(2);
  11. ls.add(3);
  12. p3("随机获取一个整数", RandomUtil.randomInt(1,1000));
  13. p3("随机获取一个字节数组", RandomUtil.randomBytes(3));
  14. p3("随机获取一个集合里的某个元素", RandomUtil.randomEle(ls));
  15. p3("随机获取一个字符串", RandomUtil.randomString(10));
  16. p3("随机获取一个大写字符串", RandomUtil.randomStringUpper(10));
  17. p3("随机获取一个数字字符串", RandomUtil.randomNumbers(10));
  18. p3("随机获取一个UUID", RandomUtil.randomUUID());
  19. p3("随机获取一个简化的UUID", RandomUtil.simpleUUID());
  20. }
  21. }

hutool 比较器工具

TestComparator

  1. package cn.hutool.test;
  2. import cn.hutool.core.collection.CollectionUtil;import cn.hutool.core.comparator.PinyinComparator;import cn.hutool.core.comparator.PropertyComparator;import cn.hutool.core.util.RandomUtil;import hutool.domain.Hero;import org.junit.Test;
  3. import java.util.ArrayList;import java.util.Collection;import java.util.List;
  4. public class TestComparator extends myHutool {
  5. @Test
  6. @Comment("属性比较器")
  7. public void test1() {
  8. List<Hero> heros = new ArrayList<>();
  9. for (int i = 0; i < 5; i++) {
  10. heros.add(new Hero("hero"+i, RandomUtil.randomInt(100)));
  11. }
  12. System.out.println("未排序的集合:");
  13. System.out.println(CollectionUtil.join(heros,"\r\n"));
  14. CollectionUtil.sort(heros,new PropertyComparator<Hero>("hp"));
  15. System.out.println("根据属性 HP 排序之后:");
  16. System.out.println(CollectionUtil.join(heros,"\r\n"));
  17. }
  18. @Test
  19. @Comment("拼音比较器")
  20. public void test2() {
  21. List<String> names = new ArrayList<>();
  22. names.add("张三");
  23. names.add("李思");
  24. names.add("王武");
  25. names.add("赵柳");
  26. p3("未排序的集合",CollectionUtil.join(names," , "));
  27. CollectionUtil.sort(names,new PinyinComparator());
  28. p3("根据拼音排序的集合",CollectionUtil.join(names," , "));
  29. }
  30. }

实体类:Hero

  1. package hutool.domain;
  2. public class Hero {
  3. public String name;
  4. public int hp;
  5. public Hero(String name, int hp) {
  6. this.name = name;
  7. this.hp = hp;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public int getHp() {
  16. return hp;
  17. }
  18. public void setHp(int hp) {
  19. this.hp = hp;
  20. }
  21. @Override
  22. public String toString() {
  23. return "Hero{" +
  24. "name='" + name + '\'' +
  25. ", hp=" + hp +
  26. '}';
  27. }
  28. }

hutool 多线程工具

TestThread

  1. package cn.hutool.test;
  2. import cn.hutool.core.thread.ThreadUtil;import cn.hutool.core.util.ArrayUtil;import org.junit.Test;
  3. public class TestThread extends myHutool {
  4. @Test
  5. @Comment("多线程工具")
  6. public void test1() {
  7. p3("所有线程", ArrayUtil.join(ThreadUtil.getThreads(),"\r\n\t\t\t\t"));
  8. p3("获取主线程",ThreadUtil.getMainThread());
  9. p3("不用捕捉异常的sleep","ThreadUtil.sleep(2000);");
  10. ThreadUtil.sleep(2000);
  11. p3("很方便的通过线程池执行任务","");
  12. for (int i = 0; i < 10; i++) {
  13. Runnable r = new Runnable(){
  14. @Override
  15. public void run() {
  16. System.out.println("\t\t当前线程是:"+Thread.currentThread());
  17. }
  18. };
  19. ThreadUtil.execute(r);
  20. }
  21. }
  22. }

hutool 缓存工具

TestCache

  1. package cn.hutool.test;
  2. import cn.hutool.cache.Cache;import cn.hutool.cache.CacheUtil;import cn.hutool.cache.file.LFUFileCache;import cn.hutool.cache.impl.TimedCache;import cn.hutool.core.collection.CollectionUtil;import cn.hutool.core.thread.ThreadUtil;import org.junit.Test;
  3. public class TestCache extends myHutool {
  4. @Test
  5. @Comment("缓存工具")
  6. public void test1() {
  7. p4("hutool的缓存,在处理缓存满了或者到期的时候,有如下几种策略:");
  8. p3("FIFOCache","first in first out , 先入先出,一旦缓存满了,先放进去的,先被清空");
  9. p3("LFUCache","least frequently used, 一旦缓存满了,用得最少的,先被清空 (命中低的数据被清空)");
  10. p3("LRUCache","least recently used, 一旦缓存满了,最久没用的,先被清空 (旧数据被清空)");
  11. p3("TimedCache","一旦时间到了,被清空 (考虑时效性)");
  12. p3("WeakCache","一旦内存满了,要垃圾回收了,优先被清空 (内存占用重要性)");
  13. p3("FileCach","把文件对象作为缓存,减少IO访问频率");// LFUCache
  14. // LRUCache least recently used
  15. // TimedCache
  16. // WeakCache
  17. // FileCach
  18. }
  19. @Test
  20. @Comment("FIFO 示例")
  21. public void test2() {
  22. p4("初始化缓存大小是 2");
  23. p4("接着向里面挨个放入1,2,3,导致缓存变满");
  24. Cache<String, Integer> cache = CacheUtil.newFIFOCache(2);
  25. cache.put("key1",1);
  26. cache.put("key2",2);
  27. cache.put("key3",3);
  28. p3("遍历缓存中的数据", CollectionUtil.join(cache,","));
  29. p4("如预料一般,最早放入的最先被清空");
  30. }
  31. @Test
  32. @Comment("LFUCache 示例")
  33. public void test3() {
  34. p4("初始化缓存大小是 2");
  35. p4("接着向里面挨个放入1,2,3,导致缓存变满");
  36. Cache<String, Integer> cache = CacheUtil.newLFUCache(2);
  37. cache.put("key1",1);
  38. cache.put("key2",2);
  39. p4("中途故意使用一次 key1");
  40. cache.get("key1");
  41. cache.put("key3",3);
  42. p3("遍历缓存中的数据",CollectionUtil.join(cache, ","));
  43. p4("如预料一般,使用频率最低的 2 的被清空");
  44. }
  45. @Test
  46. @Comment("LFUCache 示例")
  47. public void test4(){
  48. p4("初始化缓存大小是 2");
  49. p4("接着向里面挨个放入1,2,3,导致缓存变满");
  50. Cache<String,Integer> cache= CacheUtil.newLRUCache(2);
  51. cache.put("key1",1 );
  52. cache.put("key2",2 );
  53. p4("中途故意使用一次 key1");
  54. cache.get("key1");
  55. cache.put("key3",3 );
  56. p3("遍历缓存中的数据",CollectionUtil.join(cache, ","));
  57. p4("如预料一般,最久没有被使用的 2 的被清空");
  58. }
  59. @Test
  60. @Comment("TimedCache 示例")
  61. public void test5() {
  62. p4("初始化缓存大小是 2");
  63. p4("接着向里面挨个放入1,2, 分别放设置存放时间为1秒和5秒");
  64. TimedCache<Object, Object> cache = CacheUtil.newTimedCache(Integer.MAX_VALUE);
  65. cache.put("key1",1,1000);
  66. cache.put("key2",2,5000);
  67. p4("休息三秒");
  68. ThreadUtil.sleep(3000);
  69. p3("遍历缓存中的数据",CollectionUtil.join(cache,","));
  70. p4("如预料一般, 经过3秒后,1被清空了,2还在");
  71. }
  72. @Test
  73. @Comment("WeakCache 示例")
  74. public void test6(){
  75. p4("WeekCache表示当垃圾回收发生的时候,不会阻挡回收器把它回收走。");
  76. p4("请注意看描述:\"不会阻挡\", 就是说,垃圾回收真正要对它下手了,是可以下手的。");
  77. p4("但是垃圾回收发生的时候,不一定会回收所有垃圾和 week引用。");
  78. p4("正因为如此,不易观察到现象,而且不稳定,所以就不做演示了,免得误导");
  79. }
  80. @Test
  81. @Comment("FileCache 示例")
  82. public void test7(){
  83. p4("FileCache 也分 LFU, LRU 等,只是调用方式有所区别,并没有被放到 CacheUtil里,找了好一会儿才找到。。。,");
  84. //参数1:容量,能容纳的byte数
  85. //参数2:最大文件大小,byte数,决定能缓存至少多少文件,大于这个值不被缓存直接读取
  86. //参数3:超时。毫秒
  87. long capacity = 1024*1024*500; //最多500m, 太大了,内存吃不消,缓存就没法实施了
  88. long maxFileSize = 1024*1024*10; //最大10m, 文件小于这个就缓存,太大了也不缓存
  89. long timeout = 1000*60*60*24; //缓存一天,超过这个就自动从缓存里移除了
  90. LFUFileCache cache = new LFUFileCache(1024*1024*500, 500, 2000);
  91. //使用办法:
  92. //byte[] bytes = cache.getFileBytes("e:/project/hutool/img/logo.png");
  93. }
  94. }
  95. 新增父类方法p4(Object value)
  96. public void p4(Object value) {
  97. p(null, value, "", "", "format4");
  98. }
  99. 实现该方法p(null, value, "", "", "format4");
  100. if ("format4".equals(format)){
  101. System.out.printf("\t%s%n%n", value1);
  102. }

hutool 定时器工具

HutoolCronTask
任务类

  1. package hutool;
  2. import cn.hutool.core.date.DateUtil;
  3. public class HutoolCronTask implements Runnable {
  4. @Override
  5. public void run() {
  6. System.out.println(DateUtil.now() + "this is HutoolCronTask");
  7. }
  8. }

cron.settings
配置文件,cron.settings, 要放在 /resources/config 目录下
[hutool]
HutoolCronTask.run = /2 * ?

TestCron

  1. package hutool;
  2. import cn.hutool.core.date.DateUtil;import cn.hutool.cron.CronUtil;
  3. public class TestCron {
  4. public static void main(String[] args) {
  5. CronUtil.setMatchSecond(true);
  6. CronUtil.start();
  7. }
  8. }

用代码添加任务

  1. package hutool;
  2. import cn.hutool.core.date.DateUtil;import cn.hutool.cron.CronUtil;
  3. public class TestCron {
  4. public static void main(String[] args) {
  5. CronUtil.setMatchSecond(true);
  6. CronUtil.start();
  7. CronUtil.schedule("*/2 * * * * ?",new Runnable() {
  8. @Override
  9. public void run() {
  10. System.out.println(DateUtil.now()+ " 执行新任务");
  11. }
  12. });
  13. }
  14. }

四、类和对象

hutool 反射工具

TestReflection

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.ReflectUtil;import hutool.domain.Hero;import org.junit.Test;
  3. public class TestReflection extends myHutool {
  4. @Test
  5. @Comment("设置属性")
  6. public void test1() {
  7. Hero hero = new Hero();
  8. ReflectUtil.setFieldValue(hero,"name","法外狂徒张三");
  9. p3("对象通过反射设置name属性后的值",hero.getName());
  10. }
  11. @Test
  12. @Comment("调用方法")
  13. public void test2() {
  14. Hero hero = new Hero();
  15. ReflectUtil.invoke(hero,"setName","法外狂徒张三");
  16. p3("对象通过反射设置调用setName属性后的值",hero.getName());
  17. }
  18. }

hutool 类工具

其他方法
获取方法

  1. public static Set<String> getPublicMethodNames(Class<?> clazz)
  2. public static Method[] getPublicMethods(Class<?> clazz)
  3. public static List<Method> getPublicMethods(Class<?> clazz, Filter<Method> filter)
  4. public static List<Method> getPublicMethods(Class<?> clazz, Method... excludeMethods)
  5. public static List<Method> getPublicMethods(Class<?> clazz, String... excludeMethodNames)
  6. public static Method getPublicMethod(Class<?> clazz, String methodName, Class<?>... paramTypes)
  7. public static Set<String> getDeclaredMethodNames(Class<?> clazz)
  8. public static Method[] getDeclaredMethods(Class<?> clazz)
  9. public static Method getDeclaredMethodOfObj(Object obj, String methodName, Object... args)
  10. public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)

获取字段

  1. public static Field getDeclaredField(Class<?> clazz, String fieldName)
  2. public static Field[] getDeclaredFields(Class<?> clazz)

调用方法

  1. public static <T> T invoke(String classNameDotMethodName, Object[] args)
  2. public static <T> T invoke(String classNameWithMethodName, boolean isSingleton, Object... args)
  3. public static <T> T invoke(String className, String methodName, Object[] args)
  4. public static <T> T invoke(String className, String methodName, boolean isSingleton, Object[] args)

五、系统工具 

hutool 粘贴板工具

TestClipboard

  1. package cn.hutool.test;
  2. import cn.hutool.core.swing.ClipboardUtil;import org.junit.Test;
  3. public class TestClipboard extends myHutool {
  4. @Test
  5. @Comment("粘贴板工具")
  6. public void test1() {
  7. String s1 = "hutool.cn - java教程";
  8. ClipboardUtil.setStr(s1);
  9. String s2 = ClipboardUtil.getStr();
  10. p3("把如下数据通过ClipboardUtil 保存到粘贴板里",s1);
  11. p3("通过ClipboardUtil 从粘贴板里取数据",s2);
  12. //注意此文件是否真的存在
  13. String imagePath = "d:/temp.png";// Image img =ImageUtil.read(imagePath);
  14. // ClipboardUtil.setImage(img);
  15. // img = ClipboardUtil.getImage();
  16. p3("向粘贴板复制图片的用法:","ClipboardUtil.setImage(img)");
  17. p3("从粘贴板获取图片的用法:","ClipboardUtil.getImage()");
  18. }
  19. }

hutool 运行时工具

TestRuntime
运行 TestRuntime 可以看到,通过 java 运行第三方程序 “netstat -n” 之后的效果。

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.RuntimeUtil;import org.junit.Test;public class TestRuntime extends myHutool {
  3. @Test
  4. @Comment("RuntimeUtil使用举例")
  5. public void test1() {
  6. String s = RuntimeUtil.execForStr("netstat -n");
  7. System.out.println(s);
  8. }
  9. }

hutool 系统属性工具

TestSystem

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.StrUtil;import cn.hutool.system.SystemUtil;import org.junit.Test;
  3. public class TestSystem extends myHutool {
  4. @Test
  5. @Comment("系统属性工具")
  6. public void test1() {
  7. p5("java虚拟机规范", StrUtil.trim(SystemUtil.getJvmSpecInfo().toString()));
  8. p5("当前虚拟机信息",StrUtil.trim(SystemUtil.getJvmInfo().toString()));
  9. p5("java规范",StrUtil.trim(SystemUtil.getJavaSpecInfo().toString()));
  10. p5("当前java信息",StrUtil.trim(SystemUtil.getJavaInfo().toString()));
  11. p5("java运行时信息",StrUtil.trim(SystemUtil.getJavaRuntimeInfo().toString()));
  12. p5("操作系统信息",StrUtil.trim(SystemUtil.getOsInfo().toString()));
  13. p5("用户信息",StrUtil.trim(SystemUtil.getUserInfo().toString()));
  14. p5("主机信息",StrUtil.trim(SystemUtil.getHostInfo().toString()));
  15. p5("内存信息",StrUtil.trim(SystemUtil.getRuntimeInfo().toString()));
  16. }
  17. }

myHutool新增方法p5

  1. public void p5(String type1, Object value1) {
  2. p(type1, value1, "", "", "format5");
  3. }
  4. if ("format5".equals(format)) {
  5. System.out.printf("---------%s-------:%n%s %n%n", type1, value1);
  6. }

六、和文件有关的 

hutool 文件IO工具

[Hutool 里的文件IO工具有好几个

IOUtil :操作流的

FileUtil :操作文件的

FileTypeUtil: 被包含在FileUtil里了

FileReader,FileWriter:这两个基本上都在FileUtil里用了

WatchMonitor: 用来监控文件变化, 这个比较有意思,可以看看自己c盘,平时文件都有什么变化。

ClassPathResource 是class 路径下资源的获取](https://how2j.cn/k/hutool/hutool-reflect/1955.html“ \l “nowhere)

IOUtil

[IOUtil 提供的方法很多,站长把常用的列出来一下,其他不怎么常用的,有兴趣的就自己看api吧

把输入流的数据复制到输出流中](https://how2j.cn/k/hutool/hutool-reflect/1955.html“ \l “nowhere)
long copy(InputStream in, OutputStream out)
读取输入流的内容为字符串
String read(InputStream in, String charsetName)
把数据写出到输出流中
void writeUtf8(OutputStream out, boolean isCloseOut, Object… contents)

FileUtil

是否是windows系统 (通过分隔符进行判断)
boolean isWindows
追加数据
File appendString(String content, File file, String charset)
遍历当前目录及其子目录
List loopFiles(String path)
目录及其子目录所有文件的大小总和
long size(File file)
创建文件,会自动创建父文件夹。 方法名故意用linux下的命令名
File touch(String fullFilePath)
删除文件或者目录(这个很危险,会自动删除当前目录以及子目录,慎用)
boolean del(String fullFileOrDirPath)
同上
static boolean clean(String dirPath)
复制文件或者目录
File copyFile(String src, String dest, StandardCopyOption… options)
判断俩文件内容是否一样
boolean contentEquals(File file1, File file2)
获取后缀名,不带.
String extName(String fileName)
根据文件头部信息获取文件类型
String getType(File file)
读取内容为字符串
readString(String path, String charsetName)
读取内容为集合
List readLines(String path, String charset)
把字符串写入到文件
File writeString(String content, String path, String charset)
把集合写入到文件
File writeLines(Collection list, File file, String charset)
转换文件编码,第一个参数必须和文件本身编码保持一致,否则就会出错。比如一个文件是GBK的,但是在UTF默认编码的环境下看到都是乱码,就可以通过这个转换一下
File convertCharset(File file, Charset srcCharset, Charset destCharset)
指定换行符,有些文件从Linux搞来的,在window下换行会混乱,可以用这个进行转换
convertLineSeparator(File file, Charset charset, LineSeparator lineSeparator)
获取CRC32校验码
long checksumCRC32(File file)
获取Web项目下的web root路径
File getWebRoot()
根据文件后缀名 (不一定是真实格式),获取其mimetype
String getMimeType(String filePath)

WatchMonitor

这是监控 F:/game 目录下所有文件的增删改。

  1. package hutool;
  2. import cn.hutool.core.io.FileUtil;import cn.hutool.core.io.watch.WatchMonitor;import cn.hutool.core.io.watch.Watcher;import cn.hutool.core.lang.Console;
  3. import java.io.File;import java.nio.file.Path;import java.nio.file.WatchEvent;
  4. public class TestWatchMonitor {
  5. public static void main(String[] args) {
  6. File file = FileUtil.file("F:/game");
  7. //这里只监听文件或目录的修改事件
  8. WatchMonitor watchMonitor = WatchMonitor.create(file, WatchMonitor.EVENTS_ALL);
  9. watchMonitor.setWatcher(new Watcher(){
  10. @Override
  11. public void onCreate(WatchEvent<?> event, Path currentPath) {
  12. Object obj = event.context();
  13. Console.log("创建:{}-> {}", currentPath, obj);
  14. }
  15. @Override
  16. public void onModify(WatchEvent<?> event, Path currentPath) {
  17. Object obj = event.context();
  18. Console.log("修改:{}-> {}", currentPath, obj);
  19. }
  20. @Override
  21. public void onDelete(WatchEvent<?> event, Path currentPath) {
  22. Object obj = event.context();
  23. Console.log("删除:{}-> {}", currentPath, obj);
  24. }
  25. @Override
  26. public void onOverflow(WatchEvent<?> event, Path currentPath) {
  27. Object obj = event.context();
  28. Console.log("Overflow:{}-> {}", currentPath, obj);
  29. }
  30. });
  31. //设置监听目录的最大深入,目录层级大于制定层级的变更将不被监听,默认只监听当前层级目录
  32. watchMonitor.setMaxDepth(Integer.MAX_VALUE);
  33. //启动监听
  34. watchMonitor.start();
  35. }
  36. }

ClassPathResource

ClassPathResource 是专门用来读取classpath 里的数据的,很方便。
如代码所所示,读取 hutoool jar 包里的:META-INF/MANIFEST.MF 文件并打印出来了。。。

  1. package cn.hutool.test;
  2. import cn.hutool.core.io.resource.ClassPathResource;import org.junit.Test;
  3. public class TestFile {
  4. @Test
  5. public void test() {
  6. ClassPathResource resource = new ClassPathResource("META-INF/MANIFEST.MF");
  7. System.out.println(resource.readUtf8Str());
  8. }
  9. }

hutool 图片工具

因为涉及到各种图片文件,不好做演示。
缩放
scale
切割
cut
切片
slice
类型转换
convert
灰度
gray
添加文字水印
pressText
添加图片水印
pressImage
旋转
rotate
水平翻转
flip
图片变成BASE-64字符串
toBase64
创建字体
createFont
根据文字创建图片
createImage
读取图片
read
随机颜色
randomColor

3. hutool CVS工具
TestCSV

  1. package cn.hutool.test;
  2. import cn.hutool.core.io.FileUtil;import cn.hutool.core.text.csv.*;import cn.hutool.core.util.CharsetUtil;import org.junit.Test;
  3. import java.util.List;
  4. public class TestCVS extends myHutool {
  5. @Test
  6. @Comment("读写CSV")
  7. public void test1() {
  8. //写数据
  9. CsvWriter writer = CsvUtil.getWriter("test.CSV", CharsetUtil.CHARSET_UTF_8);
  10. writer.write(
  11. new String[]{"a1","b1","c1"},
  12. new String[]{"a2","b2","c2"},
  13. new String[]{"a3","b3","c3"}
  14. );
  15. //读数据
  16. CsvReader reader = CsvUtil.getReader();
  17. //从文件中读取CSV数据
  18. CsvData data = reader.read(FileUtil.file("test.csv"));
  19. List<CsvRow> rows = data.getRows();
  20. //遍历行
  21. for (CsvRow csvRow : rows){
  22. //getRawList返回一个List列表,列表的每一项为CSV中的一个单元格(既逗号分隔部分)
  23. System.out.println(csvRow.getRawList());
  24. }
  25. }
  26. }

hutool 图形验证码工具

TestCaptcha
生成的3种图形验证码,第三种表示无语。。。

  1. package cn.hutool.test;
  2. import cn.hutool.captcha.CaptchaUtil;import cn.hutool.captcha.CircleCaptcha;import cn.hutool.captcha.LineCaptcha;import cn.hutool.captcha.ShearCaptcha;import cn.hutool.core.io.IoUtil;import org.junit.Test;
  3. import java.io.OutputStream;
  4. public class TestCaptcha extends myHutool {
  5. @Test
  6. @Comment("创建 线段干扰的验证码")
  7. public void test1() {
  8. int width = 200;
  9. int height = 100;
  10. LineCaptcha captcha = CaptchaUtil.createLineCaptcha(width, height);
  11. p3("当前验证码是",captcha.getCode());
  12. String path = "F:/code/captcha1.png";
  13. captcha.write(path);
  14. }
  15. @Test
  16. @Comment("创建 圆圈干扰的验证码")
  17. public void test2() {
  18. int width = 200;
  19. int height = 100;
  20. int codeCount = 5;
  21. int circleCount = 40;
  22. CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount);
  23. p3("当前的验证码是",captcha.getCode());
  24. String path = "F:/code/captcha1.png";
  25. captcha.write(path);
  26. }
  27. @Test
  28. @Comment("创建 扭曲线干扰的验证码")
  29. public void test3() {
  30. int width = 200;
  31. int height = 100;
  32. int codeCount = 5;
  33. int thickness = 2;
  34. ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, thickness);
  35. p3("当前的验证码是",captcha.getCode());
  36. String path = "F:/code/captcha1.png";
  37. captcha.write(path);
  38. }
  39. @Test
  40. @Comment("web 页面输出")
  41. public void test4() {
  42. //junit 毕竟不是servlet 容器,拿不到 response对象, 这里是伪代码
  43. int width = 200;
  44. int height = 100;
  45. LineCaptcha captcha = CaptchaUtil.createLineCaptcha(width, height);
  46. OutputStream outputStream = null;
  47. IoUtil.close(outputStream);
  48. }
  49. }

七、需要第三方的 

hutool 邮件工具

TestMail
经过测试,是可以发送出去的。但是需要自己申请邮箱。 最好用 163的邮箱,没那么多问题,qq邮箱,foxmail,什么的都会出现奇奇怪怪的问题,不好调试。

  1. package cn.hutool.test;
  2. import cn.hutool.core.date.DateUtil;import cn.hutool.core.io.FileUtil;import cn.hutool.extra.mail.MailAccount;import cn.hutool.extra.mail.MailUtil;import org.junit.Before;import org.junit.Test;
  3. public class TestMail extends myHutool {
  4. private MailAccount account;
  5. @Before
  6. public void preparMailAccount(){
  7. account = new MailAccount();
  8. account.setHost("smtp.163.com");
  9. account.setPort(25);
  10. account.setAuth(true);
  11. account.setFrom("ithation@163.com");
  12. account.setUser("ithation@163.com");
  13. account.setPass("---密码---");
  14. }
  15. @Test
  16. @Comment("发送普通文本")
  17. public void test1() {
  18. MailUtil.send(account,"ithaotian@qq.com", "hutool 测试邮件" + DateUtil.now(), "测试内容", false);
  19. }
  20. @Test
  21. @Comment("发送HTML邮件")
  22. public void test2() {
  23. MailUtil.send(account,"ithaotian@qq.com", "hutool 测试邮件" + DateUtil.now(), "<p>测试内容</p>", true);
  24. }
  25. @Test
  26. @Comment("发送带附件的文件")
  27. public void test3() {
  28. MailUtil.send(account,"ithaotian@qq.com","hutool 测试邮件"+DateUtil.now(),"<p>测试内容</p>",true, FileUtil.file("F:/code/captcha1.png"));
  29. }
  30. }
  31. pom.xml
  32. 从现在开始,都是需要第三方包 才能使用的 hutool 功能了
  33. <dependency>
  34. <groupId>javax.mail</groupId>
  35. <artifactId>mail</artifactId>
  36. <version>1.4.7</version>
  37. </dependency>

hutool 二维码工具

pom.xml
增加zxing 用于处理二维码图片

  1. <dependency>
  2. <groupId>com.google.zxing</groupId>
  3. <artifactId>core</artifactId>
  4. <version>3.1.0</version>
  5. </dependency>

TestQR
如图所示,可以生成二维码图片
hutool - 图1

  1. package cn.hutool.test;
  2. import cn.hutool.core.io.FileUtil;import cn.hutool.extra.qrcode.QrCodeUtil;import org.junit.Test;
  3. public class TestQR extends myHutool {
  4. @Test
  5. @Comment("生成二维码图片和解析图片")
  6. public void test1() {
  7. String string = "http://hutool.cn";
  8. String path = "F:/code/qrcode.jpg";
  9. QrCodeUtil.generate(string,300,300, FileUtil.file(path));
  10. p1("字符串",string,"二维码图片",path);
  11. string = QrCodeUtil.decode(FileUtil.file(path));
  12. p1("二维码图片",path,"字符串",string);
  13. }
  14. }

hutool FTP工具

pom.xml
增加 ftp 依赖

  1. <dependency>
  2. <groupId>commons-net</groupId>
  3. <artifactId>commons-net</artifactId>
  4. <version>3.3</version>
  5. </dependency>

TestFtp

  1. package cn.hutool.test;
  2. import cn.hutool.core.io.FileUtil;import cn.hutool.extra.ftp.Ftp;import org.junit.Test;
  3. import java.io.IOException;
  4. public class TestFtp extends myHutool {
  5. @Test
  6. @Comment("上传下载")
  7. public void test1() {
  8. String localFile4Upload = "F:/code/qrcode.jpg";
  9. String localFile4Download = "F:/code/qrcode2.jpg";
  10. String remoteFolder = "/";
  11. String remoteFile = "qrcode.jpg";
  12. String ftpServer = "14.21.28.203";//这是无效的ip地址,请使用自己有效的ftp服务器ip地址
  13. String name = "ftpuser";
  14. String password = "password123";
  15. Ftp ftp = new Ftp(ftpServer, 21, name, password);
  16. boolean success = ftp.upload(remoteFolder, remoteFile, FileUtil.file(localFile4Upload));
  17. p3("上传是否成功",success);
  18. ftp.download(remoteFolder,remoteFile,FileUtil.file(localFile4Download));
  19. p3("用于上传的文件大小",FileUtil.file(localFile4Upload).length());
  20. p3("下载下来之后的文件大小",FileUtil.file(localFile4Download).length());
  21. try {
  22. ftp.close();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

八、其他

Hutool 网络工具

TestNet

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.NetUtil;import org.junit.Test;
  3. public class TestNet extends myHutool {
  4. @Test
  5. @Comment("ipv4 和 long 互换")
  6. public void test1() {
  7. String ip = "192.168.10.7";
  8. long value = 0L;
  9. value = NetUtil.ipv4ToLong(ip);
  10. ip = NetUtil.longToIpv4(value);
  11. p2("ip地址",ip,"对应的long",value);
  12. p2("long值",value,"对应的IP",ip);
  13. }
  14. @Test
  15. @Comment("判断端口和地址")
  16. public void test2() {
  17. int port1 = 80;
  18. int port2 = 680000;
  19. String ip1 = "220.181.57.216";
  20. String ip2 = "192.168.10.7";
  21. p2("端口号",port1, "是否已经被占用",!NetUtil.isUsableLocalPort(port1));
  22. p2("端口号",port2, "是否一个有效的端口号",NetUtil.isValidPort(port2));
  23. p2("ip地址",ip1, "是否是个内网地址",NetUtil.isInnerIP(ip1));
  24. p2("ip地址",ip2, "是否是个内网地址",NetUtil.isInnerIP(ip2));
  25. }
  26. @Test
  27. @Comment("其他相关操作")
  28. public void test3() {
  29. String ip = "220.181.57.216";
  30. String host = "baidu.com";
  31. p2("原ip",ip,"隐藏最后一位",NetUtil.hideIpPart(ip));
  32. p2("域名",host,"对应的IP地址",NetUtil.getIpByHost(host));
  33. p3("本机IP地址",NetUtil.localIpv4s());
  34. p3("本机MAC地址",NetUtil.getLocalMacAddress());
  35. }
  36. }

hutool 压缩工具

TestZip

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.ZipUtil;import org.junit.Test;
  3. public class TestZip extends myHutool {
  4. @Test
  5. @Comment("压缩字符串")
  6. public void test1() {
  7. String string = "hello!!!!!!!!!!!!!!!!!!";
  8. byte[] bs = ZipUtil.zlib(string, "utf-8", 4);
  9. String str2 = ZipUtil.unZlib(bs, "utf-8");
  10. p3("原字符串",string);
  11. p3("长度是",string.length());
  12. p3("zlib压缩后,长度是",bs.length);
  13. p3("unzip后得到",str2);
  14. }
  15. @Test
  16. @Comment("压缩文件")
  17. public void test2() {
  18. System.out.println("\t因为是压缩文件,不好演示,主要就是使用 zip和unzip方法,很好用,都挨个试试就知道了");
  19. }
  20. }

hutool 正则工具

TestRegex

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.ReUtil;import org.junit.Test;
  3. public class TestRegex extends myHutool {
  4. @Test
  5. @Comment("正则表达式")
  6. public void test1() {
  7. String content = "But just as he who called you is holy, so be holy in all you do; for it is written: “Be holy, because I am holy";
  8. p3("字符串",content);
  9. String regex = "\\w{5}";
  10. p3(regex + "表:","连续五个字母或者数字");
  11. Object result = ReUtil.get(regex, content, 0);
  12. p2("正则表达式",regex,"get 返回值",result);
  13. result = ReUtil.contains(regex,content);
  14. p2("正则表达式",regex,"contain 返回值",result);
  15. result = ReUtil.count(regex, content);
  16. p2("正则表达式",regex,"count 返回值", result);
  17. result = ReUtil.delAll(regex, content);
  18. p2("正则表达式",regex,"delAll 返回值", result);
  19. result = ReUtil.delFirst(regex, content);
  20. p2("正则表达式",regex,"delFirst 返回值", result);
  21. result = ReUtil.delPre(regex, content);
  22. p2("正则表达式",regex,"delPre 返回值", result);
  23. result = ReUtil.findAll(regex, content,0);
  24. p2("正则表达式",regex,"findAll 返回值", result);
  25. }
  26. }

hutool 校验工具

TestValidator

  1. package cn.hutool.test;
  2. import cn.hutool.core.lang.Validator;import org.junit.Test;
  3. public class TestValidator extends myHutool {
  4. @Test
  5. @Comment("校验器")
  6. public void test1() {
  7. String email = "123@qq.com";
  8. boolean valid = Validator.isEmail(email);
  9. p2("邮箱地址",email," 是否合法",valid);
  10. }
  11. }

归纳

Validator 把一些常用的校验工具准备好了,可以直接使用。
为空判断
isNull
isEmpty
字母,数字和下划线
isGeneral
至少多长的
isGeneral(String value, int min)
给定范围的
isGeneral(String value, int min, int max)
数字
isNumber
给定范围的数字
isBetween(Number value, Number min, Number max)
纯字母
isLetter
大小写
isUpperCase
isLowerCase
ip4
isIpv4
金额
isMoney
邮件
isEmail
手机号码
isMobile
18位身份证
isCitizenId
邮编
isZipCode
出生年月日
isBirthday
URL
isUrl
汉字
isChinese
汉字,字母,数字和下划线
isGeneralWithChinese
mac地址
isMac
中国车牌
isPlateNumber
uuid
isUUID

hutool 身份证工具

TestIdCard

  1. package cn.hutool.test;
  2. import cn.hutool.core.util.IdcardUtil;import org.junit.Test;
  3. public class TestIdCard extends myHutool {
  4. @Test
  5. @Comment("身份证检验器")
  6. public void test1() {
  7. String id15 = "510108871125243";
  8. p3("15位身份证号码",id15);
  9. p3("判断是否有效", IdcardUtil.isValidCard(id15));
  10. p3("转换为18位身份证号码",IdcardUtil.convert15To18(id15));
  11. p3("获取生日",IdcardUtil.getBirthByIdCard(id15));
  12. p3("获取年龄",IdcardUtil.getAgeByIdCard(id15));
  13. p3("获取出生年",IdcardUtil.getYearByIdCard(id15));
  14. p3("获取出生月",IdcardUtil.getMonthByIdCard(id15));
  15. p3("获取出生天",IdcardUtil.getDayByIdCard(id15));
  16. p3("获取性别",IdcardUtil.getGenderByIdCard(id15));
  17. p3("获取省份",IdcardUtil.getProvinceByIdCard(id15));
  18. }
  19. }

hutool 关闭日志

关于日志
hutool 在使用某些功能,如 HttpUtil 的时候,会出现如图所示的一行代码,表示启动了日志。

日志输出
hutool 的日志会按照如图顺序寻找日志工具。 出现步骤1的输出表示什么都没找到,用的是 jdk 自带的Log.

所以提供对应的日志配置文件,并设置输出级别,就可以把上面的日志关闭了。
hutool - 图2

log4j.properties
导入 log4j 的jar , 然后把 log4j.properties 放在 src 或者 src/main/resources 目录下就可以了。
# default properties to initialise log4j log4j.rootLogger=info,a1
log4j.appender.a1
=org.apache.log4j.ConsoleAppender log4j.appender.a1.layout=org.apache.log4j.PatternLayout log4j.appender.a1.layout.ConversionPattern=[%d{MM-dd HH:mm:ss}] %-5p - %c{1} [%t]: %m%n