One of the readers of the “Black Iron Age” commented, “Hutool is a great open source class library. Basically, there should be all the tool classes in it.” To be honest, I use Hutool a lot in my daily work, and it really helps us simplify every line of code, giving Java the elegance of a functional language, and sweeten the Java language.

However, there are still some friends in the group that do not know this open source class library, it is the first time to hear. So I decided to write an article to popularize it. After all, good wheels are recommended.

The author of Hutool said on the official website that Hutool is a word made up of Hu+tool (as if we can guess without saying it), “Hu” is used to pay tribute to his “predecessor” company, “tool” means “tool”, the homophonic is interesting, “muddlehead”, meaning “everything is muddlehead view, there is no loss. It doesn’t matter “(an open source class library, rising to the height of philosophy, the author is great).

Look at a member of the development team, a Java backend tool author actually love front-end, love digital, love beautiful women, MMMM, indeed “hard to confused” (manual dog head).

Even the PR (pull Request) specification submitted to this open source library is “sick” (hahaha) :

So much for the nonsense, come on, let’s do it!

01. Introduce Hutool

The Maven project simply needs to add the following dependencies to the POM.xml file.

<groupId>cn. Hutool </groupId> <artifactId>hutool-all</artifactId> 5.4.3</version> </dependency>Copy the code

Hutool is designed with the idea of minimizing duplication of definitions and keeping util packages as few as possible in a project. A good wheel can largely avoid “copy-and-paste,” thus saving us developers the time it takes to encapsulate common libraries and common tool methods in a project. At the same time, mature open source libraries can also minimize the bugs caused by poor encapsulation.

As the author puts it on their website:

  • Before, we opened the search engine -> search “Java MD5 encryption” -> open a blog -> copy and paste -> change to make it easier to use

So once you have Hutool, let’s go to Hutool -> secureutil.md5 ()

Hutool not only encapsulates files, streams, encryption and decrypting, transcoding, re, threads, XML, etc., but also provides the following components:

It’s a lot. It’s comprehensive, so with that in mind, I’m just going to pick a few of my favorites (between you and me, I’m trying to be lazy).

02. Type conversion

Type conversions are common in Java development, especially when you get an argument from an HttpRequest. The front end is passing an integer, but the back end can only get a string first and then call parseXXX() to convert it, plus nullability, which is tedious.

Hutool’s Convert class makes this easier by converting any possible type to the specified type, while the second argument, defaultValue, can be used to return a defaultValue if the conversion fails.

String param = "10";
int paramInt = Convert.toInt(param);
int paramIntDefault = Convert.toInt(param, 0);
Copy the code

Convert a string to a date:

String dateStr = "29 September 2020";
Date date = Convert.toDate(dateStr);
Copy the code

Convert string to Unicode:

String unicodeStr = "King of Silence two.";
String unicode = Convert.strToUnicode(unicodeStr);
Copy the code

03, date and time

DateUtil, packaged with Hutool, is much more comfortable to use.

Get the current date:

Date date = DateUtil.date();
Copy the code

Dateutil.date () actually returns DateTime. It inherits from the date object, overwrites the toString() method, and returns a string in the format YYYY-MM-DD HH: MM :ss.

If some friends want to see the time I wrote this article, output for you to see:

System.out.println(date); / / the 2020-09-29 04:28:02Copy the code

String to date:

String dateStr = "2020-09-29";
Date date = DateUtil.parse(dateStr);
Copy the code

Dateutil.parse () automatically recognizes some common formats, such as:

  • yyyy-MM-dd HH:mm:ss
  • yyyy-MM-dd
  • HH:mm:ss
  • yyyy-MM-dd HH:mm
  • yyyy-MM-dd HH:mm:ss.SSS

Can also identify with Chinese:

  • Year month day hour minute second

Format time difference:

String dateStr1 = "The 2020-09-29 22:33:23";
Date date1 = DateUtil.parse(dateStr1);

String dateStr2 = "The 2020-10-01 23:34:27";
Date date2 = DateUtil.parse(dateStr2);

long betweenDay = DateUtil.between(date1, date2, DateUnit.MS);

// Output: 2 days, 1 hour, 1 minute, 4 seconds
String formatBetween = DateUtil.formatBetween(betweenDay, BetweenFormater.Level.SECOND);
Copy the code

Horoscopes and Zodiac signs:

/ / Sagittarius
String zodiac = DateUtil.getZodiac(Month.DECEMBER.getValue(), 10);
/ / the snake
String chineseZodiac = DateUtil.getChineseZodiac(1989);
Copy the code

04. IO stream related

IO operations include read and write, and the application scenarios mainly include network operations and file operations. The native Java class reservoir is divided into character streams and byte streams. There are many types of byte streams, InputStream and OutputStream.

Hutool encapsulates IoUtil, FileUtil, FileTypeUtil, and so on.

BufferedInputStream in = FileUtil.getInputStream("hutool/origin.txt");
BufferedOutputStream out = FileUtil.getOutputStream("hutool/to.txt");
long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
Copy the code

In IO operations, file operations are relatively complex, but they are also frequently used. Almost all projects have a utility class called FileUtil or FileUtils. Hutool’s FileUtil class contains the following operations:

  • File operations: Create, delete, copy, move, and rename files and directories
  • File judgment: Determine whether a file or directory is not empty, whether it is a directory, whether it is a file, etc
  • Absolute path: Converts files in the ClassPath to absolute path files
  • File name: Obtain the primary file name and extension
  • Read operations: Include getReader and readXXX operations
  • Write operations: include getWriter and writeXXX operations

By the way, classpath.

In actual coding, we usually need to read some data from some files, such as configuration files, text files, images, etc., where do these files usually go?

Put it in the resources directory in the project structure diagram, and when the project is compiled, it will appear in the classes directory. The directory on the corresponding disk is as shown in the following figure:

When reading a file, I don’t recommend using the absolute path because the file path identifier varies from operating system to operating system. It is best to use relative paths.

Let’s say we have a file named origin.txt in SRC /resources. The file path is as follows:

FileUtil.getInputStream("origin.txt")
Copy the code

If the file is stored in SRC /resources/hutool, the path parameter is changed to:

FileUtil.getInputStream("hutool/origin.txt")
Copy the code

05. String tool

The String utility class StrUtil wrapped by Hutool is similar to StringUtils in the Apache Commons Lang package. The author thinks that Str is shorter than String, although I don’t. I like one of them, though:

String template = "{}, a silent but interesting programmer, if you like his article, please search for {} on wechat.";
String str = StrUtil.format(template, "King of Silence two."."King of Silence two.");
// Silent Wang er, a silent but interesting programmer, if you like his article, please search for silent Wang er on wechat
Copy the code

06. Reflection tool

The reflection mechanism makes Java more flexible, so in some cases, reflection can do more with less. The Hutool package ReflectUtil includes:

  • Get the constructor
  • For field
  • Getting field values
  • Access method
  • Execution methods (object methods and static methods)
package com.itwanger.hutool.reflect;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/ * * *@authorWechat search "King of Silence 2", reply keyword PDF */
public class ReflectDemo {
    private int id;

    public ReflectDemo(a) {
        System.out.println("Construction method");
    }

    public void print(a) {
        System.out.println("I am King Two of Silence.");
    }

    public static void main(String[] args) throws IllegalAccessException {
        // Build the object
        ReflectDemo reflectDemo = ReflectUtil.newInstance(ReflectDemo.class);

        // Get the constructor
        Constructor[] constructors = ReflectUtil.getConstructors(ReflectDemo.class);
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName());
        }

        // Get the field
        Field field = ReflectUtil.getField(ReflectDemo.class, "id");
        field.setInt(reflectDemo, 10);
        // Get the field value
        System.out.println(ReflectUtil.getFieldValue(reflectDemo, field));

        // Get all methods
        Method[] methods = ReflectUtil.getMethods(ReflectDemo.class);
        for (Method m : methods) {
            System.out.println(m.getName());
        }

        // Get the specified method
        Method method = ReflectUtil.getMethod(ReflectDemo.class, "print");
        System.out.println(method.getName());


        // Execution method
        ReflectUtil.invoke(reflectDemo, "print"); }}Copy the code

07. Compression tools

ZipUtil, packaged with Hutool, is optimized for the java.util.zip package. It uses a single method to compress and decompress files and directories, and automatically handles files and directories without the need for user determination. Greatly simplifies the complexity of compression and decompression.

ZipUtil.zip("hutool"."hutool.zip");
File unzip = ZipUtil.unzip("hutool.zip"."hutoolzip");
Copy the code

08, ID card tools

IdcardUtil, packaged with Hutool, can be used to authenticate id cards. It supports 15 and 18 digit id cards in mainland China and 10 digit ID cards in Hong Kong, Macao and Taiwan.

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

boolean valid = IdcardUtil.isValidCard(ID_18);
boolean valid15 = IdcardUtil.isValidCard(ID_15);
Copy the code

09. Extend HashMap

Hashmaps in Java are strongly typed, while the Dict encapsulated by Hutool is less restrictive about the types of keys.

Dict dict = Dict.create()
        .set("age".18)
        .set("name"."King of Silence two.")
        .set("birthday", DateTime.now());

int age = dict.getInt("age");
String name = dict.getStr("name");
Copy the code

10. Console printing

It is often necessary to use System.out to print the results of local encoding, but often some complex objects do not support direct printing, such as Arrays, need to call Arrays.toString. The Console class encapsulated by Hutool borroweth from the JavaScript console.log() to make printing a very convenient way.

/ * * *@authorWechat search "King of Silence 2", reply keyword PDF */
public class ConsoleDemo {
    public static void main(String[] args) {
        // Print the string
        Console.log("King Of Silence ii, an interesting programmer.");

        // Print the string template
        Console.log("Luoyang is the ancient capital of {} Dynasty.".13);

        int [] ints = {1.2.3.4};
        // Print the arrayConsole.log(ints); }}Copy the code

11. Field validators

When doing Web development, the back end usually needs to validate the data submitted by the form. Hutool-encapsulated Validators can perform a number of valid conditional validations:

  • Is it an email?
  • Is it IP V4, V6
  • Is it a phone number?
  • , etc.

Validator.isEmail("King of Silence two.");
Validator.isMobile("itwanger.com");
Copy the code

12. Two-way Map lookup

Guava provides a special Map structure called BiMap, which implements a bidirectional lookup function. You can find a value based on a key or a key based on a value. Hutool also provides this Map structure.

BiMap<String, String> biMap = new BiMap<>(new HashMap<>());
biMap.put("wanger"."King of Silence two.");
biMap.put("wangsan"."King Of Silence iii");

// get value by key
biMap.get("wanger");
biMap.get("wangsan");

// get key by value
biMap.getKey("King of Silence two.");
biMap.getKey("King Of Silence iii");
Copy the code

In my actual development work, I prefer to use Guava’s BiMap rather than Hutool’s. I mention here that I found a mistake in the Hutool online document and made an issue of it (it shows my meticulous heart and a pair of clear and bright eyes).

13. Picture tools

Hutool encapsulates ImgUtil to scale, crop, convert images to black and white, and watermark them.

Zoom in and out:

ImgUtil.scale(
        FileUtil.file("hutool/wangsan.jpg"),
        FileUtil.file("hutool/wangsan_small.jpg"),
        0.5 f
);
Copy the code

Crop the picture:

ImgUtil.cut(
        FileUtil.file("hutool/wangsan.jpg"),
        FileUtil.file("hutool/wangsan_cut.jpg"),
        new Rectangle(200.200.100.100));Copy the code

Add watermark:

ImgUtil.pressText(//
        FileUtil.file("hutool/wangsan.jpg"),
        FileUtil.file("hutool/wangsan_logo.jpg"),
        "King of Silence two.", Color.WHITE,
        new Font("Black", Font.BOLD, 100),
        0.0.0.8 f
);
Copy the code

It’s a chance to show everyone the handsome face of my second brother.

14. Configuration file

Properties, a widely used configuration file in Java, has one particular complaint: it doesn’t support Chinese. Every time you use it, if you want to store Chinese characters, you have to use an IDE plug-in to convert them to Unicode symbols, which are unreadable from the command line.

Thus, Hutool Setting was applied. In addition to being compatible with the Properties file format, Setting provides some unique features, including:

  • Various encoding methods are supported
  • Variable support
  • Grouping support

The entire configuration file example.setting is as follows:

Name = age=18Copy the code

To read and update the configuration file:

/ * * *@authorWechat search "King of Silence 2", reply keyword PDF */
public class SettingDemo {
    private final static String SETTING = "hutool/example.setting";
    public static void main(String[] args) {
        // Initialize the Setting
        Setting setting = new Setting(SETTING);

        / / read
        setting.getStr("name"."King of Silence two.");

        // Automatically load when the configuration file is changed
        setting.autoLoad(true);

        // Add key-value pairs by code
        setting.set("birthday"."29 September 2020"); setting.store(SETTING); }}Copy the code

15. Log factory

The LogFactory encapsulated by Hutool is compatible with various logging frameworks and is very easy to use.

/ * * *@authorWechat search "King of Silence 2", reply keyword PDF */
public class LogDemo {
    private static final Log log = LogFactory.get();

    public static void main(String[] args) {
        log.debug("Hard to get confused."); }}Copy the code

Logfactory.get () is used to automatically identify the imported logging framework, so as to create the facade Log object corresponding to the logging framework, and then call debug(), info() and other methods to output logs.

If you don’t want to create a Log object, you can use StaticLog, which, as the name suggests, is a logging class that provides static methods.

StaticLog.info("Oh great {}."."An essay by the second Silent King.");
Copy the code

16. Cache tools

CacheUtil is a shortcut class for creating caches encapsulated by Hutool. You can create different cache objects:

  • FIFOCache: First in, first out, elements are added to the cache until the cache is full. When the cache is full, the expired cache objects are cleared. If the cache is still full, the first in cache is deleted.
Cache<String, String> fifoCache = CacheUtil.newFIFOCache(3);
fifoCache.put("key1"."King Of Silence.");
fifoCache.put("key2"."King of Silence two.");
fifoCache.put("key3"."King Of Silence iii");
fifoCache.put("key4"."King of Silence iv");

// The size is 3, so key1 is cleared when key3 is put in
String value1 = fifoCache.get("key1");
Copy the code
  • LFUCache, the least used, determines whether an object is continuously cached according to the number of uses. When the cache is full, the expired object is cleared. If the cache is still full, the least accessed object is cleared and the number of accesses to other objects is subtracted from the minimum number of accesses, so that new objects can be equitably counted.
Cache<String, String> lfuCache = CacheUtil.newLFUCache(3);

lfuCache.put("key1"."King Of Silence.");
// Use times +1
lfuCache.get("key1");
lfuCache.put("key2"."King of Silence two.");
lfuCache.put("key3"."King Of Silence iii");
lfuCache.put("key4"."King of Silence iv");

// since the cache size is only 3, when the fourth element is added, the least used element is removed (2,3 is removed).
String value2 = lfuCache.get("key2");
String value3 = lfuCache.get("key3");
Copy the code
  • LRUCache, the most recent unused, determines whether the object is continuously cached according to the usage time. When the object is accessed, it is put into the cache. When the cache is full, the object that has been unused for the longest time will be removed.
Cache<String, String> lruCache = CacheUtil.newLRUCache(3);

lruCache.put("key1"."King Of Silence.");
lruCache.put("key2"."King of Silence two.");
lruCache.put("key3"."King Of Silence iii");
// Use time is near
lruCache.get("key1");
lruCache.put("key4"."King of Silence iv");

// Since the cache capacity is only 3, when the fourth element is added, the longest used element will be removed (2)
String value2 = lruCache.get("key2");
System.out.println(value2);
Copy the code

17, encryption and decryption

There are three types of encryption:

  • Symmetric encryption is available, such as AES and DES
  • Asymmetric encryption: Such as RSA and DSA
  • Digest, such as MD5, SHA-1, SHA-256, and HMAC

Hutool is packaged for all three cases:

  • SymmetricCrypto
  • AsymmetricCrypto
  • Digester is encrypted

The SecureUtil quick encryption utility class has these methods:

1) Symmetric encryption

  • SecureUtil.aes
  • SecureUtil.des

2) Asymmetric encryption

  • SecureUtil.rsa
  • SecureUtil.dsa

3) Abstract encryption

  • SecureUtil.md5
  • SecureUtil.sha1
  • SecureUtil.hmac
  • SecureUtil.hmacMd5
  • SecureUtil.hmacSha1

Just write a simple example as a reference:

/ * * *@authorWechat search "King of Silence 2", reply keyword PDF */
public class SecureUtilDemo {
    static AES aes = SecureUtil.aes();
    public static void main(String[] args) {
        String encry = aes.encryptHex("King of Silence two."); System.out.println(encry); String oo = aes.decryptStr(encry); System.out.println(oo); }}Copy the code

18. Other class libraries

There are many libraries in Hutool. In particular, there are some further encapsulation of third-party libraries, such as MailUtil, QrCodeUtil and EmojiUtil. You can refer to Hutool’s official documentation: www.hutool.cn/

Project source address: github.com/looly/hutoo…

PS: If you need a Java book list, I found a treasure trove of books on GitHub. If you need it, you can get it by yourself. The address is as follows:

Github.com/itwanger/Ja…

Finally, ask for a like every day, full of dry goods, I do for respect, you feel free 😑