大家在系统研发过程中,总是会遇到需要自己自定义工具类的情况,做一些数据转换、字符串操作、日期处理、加解密、编解码、金额计算等等等等,每次做系统都会要把这些代码拷贝来拷贝去,费时费力还不优雅。
做java的应该有一部分知道这个工具,hutool,我可以称它为JAVA的宝藏工具了,一应俱全,一个pom引入依赖,再也不需要自己写工具类了,你的工程里甚至都不需要util这个package了。
下面我们来看看hutool都有哪些宝藏功能吧。
包含如下组件:
工程pom引入
1
2
3
4
5
|
< dependency > < groupId >cn.hutool</ groupId > < artifactId >hutool-all</ artifactId > < version >5.7.5</ version > </ dependency > |
下面就我自己的一些实验,贴一些常用代码示例吧,后面大家自己尝试下,还是非常好用的
字符串、时间、金额转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
@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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
@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毫秒
有限状态自动机-敏感词搜索
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@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); } |
[中国, 移动, 中国, 中国, 移动, 杭州, 杭州]
加解密
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
@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中文
文件
1
2
3
4
5
|
@Test public void testFile() { File file = FileUtil.newFile( "/apprun/test" + File.separator + "chiweitest-" + RandomUtil.randomString( 10 ) + ".txt" ); FileUtil.touch(file); } |
雪花算法-ID生成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
@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
网络相关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@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相关
1
2
3
4
|
@Test public void testUrl() { System.out.println(URLUtil.toURI( "//www.zzvips.com/df/sdf/df" ).getHost()); } |
www.zzvips.com
其它还有很多很多,像图形验证码、图片处理、正则、身份证、脱敏、压缩、XML等,总之一旦用上了应该就爱上了,代码优雅了很多。
PS:HUTOOL里面的HTTPUTIL,大家别用,实际工作中用apache或者其它的,因为hutool里的所有工具类源码是不引入外部其它依赖的,所以它的http工具类是没有连接池的,实际生产中应用会有很大的风险,大家摒弃。
到此这篇关于JAVA宝藏工具hutool的使用的文章就介绍到这了,更多相关JAVA hutool内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7023259516221440036