JAVA寶藏工具hutool的使用

大傢在系統研發過程中,總是會遇到需要自己自定義工具類的情況,做一些數據轉換、字符串操作、日期處理、加解密、編解碼、金額計算等等等等,每次做系統都會要把這些代碼拷貝來拷貝去,費時費力還不優雅。

做java的應該有一部分知道這個工具,hutool,我可以稱它為JAVA的寶藏工具瞭,一應俱全,一個pom引入依賴,再也不需要自己寫工具類瞭,你的工程裡甚至都不需要util這個package瞭。

下面我們來看看hutool都有哪些寶藏功能吧。

hutool官網地址

包含如下組件:

工程pom引入

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

下面就我自己的一些實驗,貼一些常用代碼示例吧,後面大傢自己嘗試下,還是非常好用的

字符串、時間、金額轉換

@Test
 public void testConvert() {
  /**
   * 字符串編碼轉換
   */
  String a = "Hello 中國";
  String hex = Convert.toHex(a, CharsetUtil.CHARSET_UTF_8);
  String raw = Convert.hexToStr(hex, CharsetUtil.CHARSET_UTF_8);
  System.out.println(raw);
  /**
   * 時間轉換,毫秒轉成XX小時等
   */
  long b = 1000 * 60 * 60 * 24;
  long mins = Convert.convertTime(b, TimeUnit.MILLISECONDS, TimeUnit.HOURS);
  System.out.println(mins);
  /**
   * 金額大小寫轉換
   */
  double c = 288.66;
  System.out.println(Convert.digitToChinese(c));

 }

Hello 中國
24
貳佰捌拾捌元陸角陸分

日期1

@Test
 public void testDateTime() throws InterruptedException {
  /**
   * 當前時間
   */
  Date now = DateUtil.date();
  System.out.println(now);
  String nowString = DateUtil.now();
  System.out.println(nowString);
  /**
   * 當前日期
   */
  String nowDate = DateUtil.today();
  System.out.println(nowDate);

  /**
   * 字符串轉日期 yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm yyyy-MM-dd
   * HH:mm:ss.SSS
   * 
   * DatePattern
   */
  String dateStr = "2021-2-12";
  System.out.println(DateUtil.parse(dateStr));
  System.out.println(DateUtil.parse(dateStr, "yyyy-MM-dd"));

  /**
   * 獲取Date對象的某個部分
   */
  System.out.println(DateUtil.year(now));
  System.out.println(DateUtil.month(now) + 1);
  System.out.println(DateUtil.dayOfMonth(now));
  System.out.println(DateUtil.hour(now, true));
  System.out.println(DateUtil.minute(now));
  System.out.println(DateUtil.second(now));

  /**
   * 開始和結束時間
   */
  System.out.println(DateUtil.beginOfDay(now));
  System.out.println(DateUtil.endOfDay(now));

  /**
   * 時間偏移
   */
  System.out.println(DateUtil.offsetHour(now, 3));
  System.out.println(DateUtil.yesterday());

 }

2021-10-26 14:26:12
2021-10-26 14:26:12
2021-10-26
2021-02-12 00:00:00
2021-02-12 00:00:00
2021
10
26
14
26
12
2021-10-26 00:00:00
2021-10-26 23:59:59
2021-10-26 17:26:12
2021-10-25 14:26:13

日期2

@Test
 public void testDateTime2() throws InterruptedException {
  /**
   * 當前時間
   */
  Date now = DateUtil.date();
  System.out.println(now);
  String nowString = DateUtil.now();
  System.out.println(nowString);
  /**
   * 時間差
   */
  Date from = DateUtil.date();
  Date end = DateUtil.offsetMillisecond(from, 988989898);
  System.out.println(DateUtil.between(from, end, DateUnit.HOUR));
  System.out.println(DateUtil.between(from, end, DateUnit.DAY));
  /**
   * 格式化時間差,默認精確到毫秒差距
   */
  System.out.println("差:" + DateUtil.formatBetween(from, end));

  /**
   * 計時器
   */
  TimeInterval timer = DateUtil.timer();
  Thread.sleep(2000L);
  System.out.println(timer.interval() + " ms");
  timer.intervalRestart();
  System.out.println(timer.intervalMinute() + " min");

  /**
   * 格式化字符串 DatePattern
   */

  /**
   * 農歷
   */
  ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate("2020-08-28"));
  String cyclicalYmd = chineseDate.getCyclicalYMD();
  System.out.println(cyclicalYmd);

  /**
   * 對JDK 8 LocalDateTime和LocalDate的支持
   */
 }

2021-10-26 14:26:47
2021-10-26 14:26:47
274
11
差:11天10小時43分9秒898毫秒

有限狀態自動機-敏感詞搜索

@Test
 public void testDfa() {
  WordTree tree = new WordTree();
  tree.addWord("中國");
  tree.addWord("移動");
  tree.addWord("杭州");
  tree.addWord("移動通信");
  tree.addWord("杭州市");
  tree.addWord("中國人");

  String text = "中國移動在中國,都是中國人,移動杭研在杭州,杭州市";

  List<String> match = tree.matchAll(text, -1, false, false);
  System.out.println(match);
 }

[中國, 移動, 中國, 中國, 移動, 杭州, 杭州]

加解密

@Test
 public void testEncDec() {
  String cont = "Hello";
  String key = "Yw/Vz4kpJUv0+E/4/LuZEA==";
  System.out.println("aes key = " + key);
  AES aes = SecureUtil.aes(Base64.decode(key));
  byte[] encrypt = aes.encrypt(cont);
  String enc = Base64.encode(encrypt);
  System.out.println("密文:" + enc);
  byte[] decrypt = aes.decrypt(enc);
  System.out.println(new String(decrypt));

  String str = SecureUtil.md5(cont);
  System.out.println("MD5: " + str);
  System.out.println("MD5 16位: " + DigestUtil.md5Hex16(cont));
  System.out.println("SHA-256:" + DigestUtil.sha256Hex("Admin@888" + "9348ierj8truigjf03wioekrutgfhj"));

  // RSA
  RSA rsa = new RSA();
  String privateKey = rsa.getPrivateKeyBase64();
  String publicKey = rsa.getPublicKeyBase64();
  System.out.println("私鑰:" + privateKey);
  System.out.println("公鑰:" + publicKey);
  String rsaEnc = rsa.encryptBase64(cont, KeyType.PublicKey);
  System.out.println("加密後:" + rsaEnc);
  System.out.println("解密後:" + rsa.decryptStr(rsaEnc, KeyType.PrivateKey));
  PublicKey publicK = rsa.getPublicKey();
  String modulus = HexUtil.encodeHexStr(((RSAPublicKey) publicK).getModulus().toByteArray());
  String exponent = HexUtil.encodeHexStr(((RSAPublicKey) publicK).getPublicExponent().toByteArray());
  System.out.println(modulus);
  System.out.println(exponent);

  HMac mac = new HMac(HmacAlgorithm.HmacSHA256, "password".getBytes());

  // b977f4b13f93f549e06140971bded384
  String macHex1 = mac.digestHex("123");
  System.out.println("HAMC - " + macHex1);
  // 3DES加密
  String content = "test中文";

  byte[] desKey = SecureUtil.generateKey(SymmetricAlgorithm.DESede.getValue()).getEncoded();
  SymmetricCrypto des = new SymmetricCrypto(SymmetricAlgorithm.DESede, desKey);
  // 加密
  byte[] desEnc = des.encrypt(content);
  // 解密
  byte[] desDec = des.decrypt(desEnc);
  // 加密為16進制字符串(Hex表示)
  String encryptHex = des.encryptHex(content);
  // 解密為字符串
  //String decryptStr = des.decryptStr(encryptHex);
  System.out.println("3DES解密串:" + new String(desDec));
 }

aes key = Yw/Vz4kpJUv0+E/4/LuZEA==
密文:xNNdbJKZ/Ml4AWWD8YwO6A==
Hello
MD5: 8b1a9953c4611296a827abf8c47804d7
MD5 16位: c4611296a827abf8
SHA-256:01a83492e88f9a138e5ca0fd3ddb29b233088c70fdf2f1f511a6683b9e725f1d
私鑰:MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMSTmbFNps1kNWXy/upzcMFvCdiMc6awisow6NZbyuEMs4JvGBt0SvvV51GonnUgPGXHD/BZ5Yq/V/V9Tq6bvy875gy8xyH5AXuRzboOnkKy2XtEsZOwCiKWeBcigWiyFuV/I7kK6WvAT/CJ5JyQabHzas4vZMKBSOg68cToPW3XAgMBAAECgYBcG50ESxJBYxbyMi3nxTesK089vHHkRQyDOO+goVoqoTzrfQqasp7/6XZ9+LhmwTgLqH57bGP14zpfuNtJTYkC0p+CnPPryfCaLxlIcypwmsHHoUSnYgZHAgybF+dDqHM4l9rrEXKpu8kj+Y+V7QbLfmooSPtHccrp/SvFXqqsQQJBAOF8iRyTbFOi77NjpdO1z1SwliyEj+uabJxCQsX0Jtghw1+tT7+UNtMSzrW/hKZ3hXBQmfNml/dPchBpHZJ9Km8CQQDfLYwO/aYf2OSjqZuLv7QMvczCcKK9jZ0qO3SesPmPEitVje3xaqfATBtNurkJ0bCv32zdF71BBrw55E02eMcZAkEAkBh+oqVPb69LUS9X9JBWG3/xqCdataxsxfrOIySggjQpX4Yo1XwJASAeuyTVx2/P9XN8voAMkz3Q3c3e2RNlvwJBAIG1DgaUYp11yARaib1h0DnrgXqsTdkO2f32iiPExXXiYG8byuOZUh+P2/qEABD13tOIbdPdfS+yw2h+CGYVMdkCQQDIN78dp2gVMnczWddP/Ak+ytSLhvsxeGnVIABw+55kXKyOg9ZolqRuFxv5wnscWQrKH7hzy6ZNmcI/q+enTtb4
公鑰:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEk5mxTabNZDVl8v7qc3DBbwnYjHOmsIrKMOjWW8rhDLOCbxgbdEr71edRqJ51IDxlxw/wWeWKv1f1fU6um78vO+YMvMch+QF7kc26Dp5Cstl7RLGTsAoilngXIoFoshblfyO5CulrwE/wieSckGmx82rOL2TCgUjoOvHE6D1t1wIDAQAB
加密後:SF+hCQbOD5feqnE+codoDaODePYJvcvklrOZztBtoE3neNtcjAaCwAF+TzvMoELI5DDmaT2jVa5HObeW7SW2fBQ1f3xN+674z1GeblYXyo0Mr3LZmpFl5d2+VtpFGkewzBS77ThtMkk34MCq3b3nlA6DG65LC67xnDHHOtVshU8=
解密後:Hello
00c49399b14da6cd643565f2feea7370c16f09d88c73a6b08aca30e8d65bcae10cb3826f181b744afbd5e751a89e75203c65c70ff059e58abf57f57d4eae9bbf2f3be60cbcc721f9017b91cdba0e9e42b2d97b44b193b00a22967817228168b216e57f23b90ae96bc04ff089e49c9069b1f36ace2f64c28148e83af1c4e83d6dd7
010001
HAMC – c58e5f636d1bfdfbd351d9469c308519fe6695f69c08d5f98198459c86f2a746
3DES解密串:test中文

文件

@Test
 public void testFile() {
  File file = FileUtil.newFile("/apprun/test" + File.separator + "chiweitest-" + RandomUtil.randomString(10) + ".txt");
  FileUtil.touch(file);
 }

雪花算法-ID生成

@Test
 public void testId() throws InterruptedException {
  int machine = getMachinePiece();
  int process = getProcessPiece();
  System.out.println(machine + "--" + process);
  System.out.println((machine & 31) + "--" + (process & 31));
  Snowflake sf = IdUtil.getSnowflake();
  // IdUtil.createSnowflake(machine&31, process&31);
  Map<Long, String> ids = MapUtil.newConcurrentHashMap();
  int counter = 10;
  int threadNum = 2;
  TimeInterval timer = DateUtil.timer();

  ConcurrencyTester tester = ThreadUtil.concurrencyTest(threadNum, () -> {
   // 測試的邏輯內容
   for (int i = 0; i < counter; i++) {
    ids.put(sf.nextId(), "");
    // String temp = IdUtil.randomUUID();
    // ids.add(IdUtil.randomUUID());
   }
  });

  // 獲取總的執行時間,單位毫秒
  Console.log(tester.getInterval());

  // 獲取總的執行時間,單位毫秒
  System.out.println(timer.interval() + " ms");
  System.out.println("SIZE:" + ids.size());
  System.out.println(ids);
  System.out.println(Long.MAX_VALUE);
 }

738459648–18962
0–18
39
45 ms
SIZE:20
{1452885332411842562=, 1452885332411842563=, 1452885332411842560=, 1452885332411842561=, 1452885332411842566=, 1452885332411842567=, 1452885332411842564=, 1452885332411842565=, 1452885332411842570=, 1452885332411842571=, 1452885332411842568=, 1452885332411842569=, 1452885332411842574=, 1452885332411842575=, 1452885332411842572=, 1452885332411842573=, 1452885332411842578=, 1452885332411842579=, 1452885332411842576=, 1452885332411842577=}
9223372036854775807

網絡相關

@Test
 public void testNet() {
  String ip = "192.168.2.65";
  long ipLong = 2130706433L;
  String long2ip = NetUtil.longToIpv4(ipLong);
  System.out.println(long2ip);
  long ip2long = NetUtil.ipv4ToLong(ip);
  System.out.println(ip2long);
  // 端口探測
  System.out.println("端口是否連通:" + NetUtil.isUsableLocalPort(6379));
  System.out.println("端口是否有效:" + NetUtil.isValidPort(77777));
  // IP脫敏
  System.out.println(NetUtil.hideIpPart(ip));
  // 獲取網卡信息
  System.out.println(NetUtil.getNetworkInterfaces());
  // eth4 (Realtek PCIe GBE Family Controller)
  System.out.println(NetUtil.getNetworkInterface("eth4"));
  System.out.println(NetUtil.LOCAL_IP);
  System.out.println("=============================");
  System.out.println(NetUtil.getLocalHostName());

 }

127.0.0.1
3232236097
端口是否連通:true
端口是否有效:false
192.168.2.*
[name:lo (Software Loopback Interface 1), name:net0 (WAN Miniport (SSTP)), name:net1 (WAN Miniport (L2TP)), name:net2 (WAN Miniport (PPTP)), name:ppp0 (WAN Miniport (PPPOE)), name:eth0 (WAN Miniport (IPv6)), name:eth1 (WAN Miniport (Network Monitor)), name:eth2 (WAN Miniport (IP)), name:ppp1 (RAS Async Adapter), name:net3 (WAN Miniport (IKEv2)), name:eth3 (Bluetooth 設備(個人區域網)), name:net4 (Bluetooth 設備(RFCOMM 協議 TDI)), name:eth4 (Realtek PCIe GBE Family Controller), name:wlan0 (Intel(R) Dual Band Wireless-AC 7260), name:net5 (Bluetooth 設備(RFCOMM 協議 TDI) #2), name:eth5 (Bluetooth 設備(個人區域網) #2), name:net6 (Microsoft 6to4 Adapter), name:eth6 (SecTap Adapter), name:eth7 (Sangfor SSL VPN CS Support System VNIC), name:net7 (Microsoft ISATAP Adapter #7), name:eth8 (TAP-Windows Adapter V9), name:net8 (Microsoft ISATAP Adapter #5), name:eth9 (VirtualBox Host-Only Ethernet Adapter), name:eth10 (Gateway NC Adapter), name:net9 (Microsoft ISATAP Adapter), name:net10 (Microsoft ISATAP Adapter #2), name:net11 (Microsoft ISATAP Adapter #6), name:net12 (Microsoft ISATAP Adapter #8), name:net13 (Microsoft ISATAP Adapter #3), name:net14 (Microsoft ISATAP Adapter #4), name:wlan1 (Microsoft Virtual WiFi Miniport Adapter), name:eth11 (Realtek PCIe GBE Family Controller-VirtualBox NDIS Light-Weight Filter-0000), name:eth12 (Realtek PCIe GBE Family Controller-QoS Packet Scheduler-0000), name:eth13 (Realtek PCIe GBE Family Controller-WFP LightWeight Filter-0000), name:eth14 (Realtek PCIe GBE Family Controller-Npcap Packet Driver (NPCAP)-0000), name:wlan2 (Intel(R) Dual Band Wireless-AC 7260-VirtualBox NDIS Light-Weight Filter-0000), name:wlan3 (Intel(R) Dual Band Wireless-AC 7260-QoS Packet Scheduler-0000), name:eth15 (Realtek PCIe GBE Family Controller-VpnCDrv LightWeight Filter-0000), name:eth16 (SecTap Adapter-VirtualBox NDIS Light-Weight Filter-0000), name:eth17 (SecTap Adapter-QoS Packet Scheduler-0000), name:eth18 (SecTap Adapter-WFP LightWeight Filter-0000), name:wlan4 (Intel(R) Dual Band Wireless-AC 7260-Npcap Packet Driver (NPCAP)-0000), name:eth19 (SecTap Adapter-Npcap Packet Driver (NPCAP)-0000), name:eth20 (WAN Miniport (Network Monitor)-Npcap Packet Driver (NPCAP)-0000), name:eth21 (WAN Miniport (Network Monitor)-VpnCDrv LightWeight Filter-0000), name:eth22 (WAN Miniport (Network Monitor)-QoS Packet Scheduler-0000), name:eth23 (WAN Miniport (IP)-Npcap Packet Driver (NPCAP)-0000), name:eth24 (WAN Miniport (IP)-VpnCDrv LightWeight Filter-0000), name:eth25 (WAN Miniport (IP)-QoS Packet Scheduler-0000), name:eth26 (WAN Miniport (IPv6)-Npcap Packet Driver (NPCAP)-0000), name:eth27 (WAN Miniport (IPv6)-VpnCDrv LightWeight Filter-0000), name:eth28 (WAN Miniport (IPv6)-QoS Packet Scheduler-0000), name:eth29 (Sangfor SSL VPN CS Support System VNIC-VirtualBox NDIS Light-Weight Filter-0000), name:eth30 (Sangfor SSL VPN CS Support System VNIC-QoS Packet Scheduler-0000), name:eth31 (Sangfor SSL VPN CS Support System VNIC-WFP LightWeight Filter-0000), name:eth32 (SecTap Adapter-VpnCDrv LightWeight Filter-0000), name:eth33 (Sangfor SSL VPN CS Support System VNIC-VpnCDrv LightWeight Filter-0000), name:eth34 (TAP-Windows Adapter V9-VirtualBox NDIS Light-Weight Filter-0000), name:eth35 (TAP-Windows Adapter V9-QoS Packet Scheduler-0000), name:eth36 (TAP-Windows Adapter V9-WFP LightWeight Filter-0000), name:wlan5 (Intel(R) Dual Band Wireless-AC 7260-Virtual WiFi Filter Driver-0000), name:eth37 (TAP-Windows Adapter V9-Npcap Packet Driver (NPCAP)-0000), name:eth38 (Gateway NC Adapter-VirtualBox NDIS Light-Weight Filter-0000), name:eth39 (Gateway NC Adapter-QoS Packet Scheduler-0000), name:eth40 (Gateway NC Adapter-WFP LightWeight Filter-0000), name:eth41 (Gateway NC Adapter-Npcap Packet Driver (NPCAP)-0000), name:eth42 (TAP-Windows Adapter V9-VpnCDrv LightWeight Filter-0000), name:eth43 (Bluetooth 設備(個人區域網) #2-Npcap Packet Driver (NPCAP)-0000), name:eth44 (Gateway NC Adapter-VpnCDrv LightWeight Filter-0000), name:wlan6 (Intel(R) Dual Band Wireless-AC 7260-Native WiFi Filter Driver-0000), name:wlan7 (Intel(R) Dual Band Wireless-AC 7260-VpnCDrv LightWeight Filter-0000), name:wlan8 (Intel(R) Dual Band Wireless-AC 7260-WFP LightWeight Filter-0000), name:ppp2 (RAS Async Adapter-Npcap Packet Driver (NPCAP)-0000)]
name:eth4 (Realtek PCIe GBE Family Controller)
127.0.0.1
=============================
chiwei-PC

URL相關

@Test
 public void testUrl() {
  System.out.println(URLUtil.toURI("//www.jb51.net/df/sdf/df").getHost());
 }

www.jb51.net

其它還有很多很多,像圖形驗證碼、圖片處理、正則、身份證、脫敏、壓縮、XML等,總之一旦用上瞭應該就愛上瞭,代碼優雅瞭很多。

PS:HUTOOL裡面的HTTPUTIL,大傢別用,實際工作中用apache或者其它的,因為hutool裡的所有工具類源碼是不引入外部其它依賴的,所以它的http工具類是沒有連接池的,實際生產中應用會有很大的風險,大傢摒棄。

到此這篇關於JAVA寶藏工具hutool的使用的文章就介紹到這瞭,更多相關JAVA hutool內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: