“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

“Hutool is a great open source library. It basically has the right tools. It has all of them.” To be honest, I use Hutool a lot in my work, and it really helps us simplify every line of code, give Java the elegance of a functional language, and make the Java language “sweet.”

PS: In order to help more Java enthusiasts, the Path to Java Programmer Advancement has been open-source on GitHub (this article has been included). This column has received 598 stars so far. If you like this column and think it is helpful, you can click a STAR, which is also convenient for more systematic learning in the future!

Github.com/itwanger/to…

The author of Hutool said on the official website that Hutool is a coinage of Hu+tool (as if needless to say, we can also guess), “Hu” is used to pay tribute to his “predecessor” company, “tool” means tool, homonym is interesting, “confused”, meaning the pursuit of “everything is confused view, no matter what loss, It doesn’t matter “(an open source class library, elevated to philosophical heights by the author).

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

That’s enough bullshit. Let’s go! Let’s go!

Introduce Hutool

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

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

The idea behind Hutool is to minimize duplicate definitions and keep util packages in the project as few as possible. A good wheel can largely avoid copy-and-paste, thus saving us developers time wrapping common libraries and common utility methods in our projects. At the same time, mature open source libraries can also avoid bugs caused by incomplete packaging to the maximum extent.

As the author puts it on his website:

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

Hutool -> secureUtil.md5 ()

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

It’s a lot, it’s a lot, and with that in mind, I’ll just pick a few that I like (and between you and me, I just want to be lazy).

02. Type conversion

Type conversion is very common in Java development, especially when the parameter from HttpRequest, the front end is passed the integer, but the back end can only get the string, and then call parseXXX() method to convert, but also null, very tedious.

Hutool’s Convert class simplifies this operation by converting any possible type to the specified type, while the second parameter 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 = September 29, 2020;
Date date = Convert.toDate(dateStr);
Copy the code

Convert strings to Unicode:

String unicodeStr = "Silent King II.";
String unicode = Convert.strToUnicode(unicodeStr);
Copy the code

03. Date and time

DateUtil is much more comfortable to use than the JDK’s built-in Date and Calendar.

Get the current date:

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

Dateutil.date () returns a DateTime that inherits from the date object and overrides the toString() method to return a string in the format YYYY-MM-DD HH: MM: SS.

If you want to see how long it took me to write this article, output it 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 commonly used 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 recognize Chinese:

  • Year month day hour minute second

Formatting 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

Signs and zodiac signs:

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

04. I/O flow correlation

IO operation includes read and write, application scenarios mainly include network operation and file operation, native Java class reservoir character stream and byte stream, byte stream InputStream and OutputStream there are many, many kinds, use it makes people’s scalp tingle.

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, the file operation is relatively complex, but also used very frequently, almost all projects lie in a utility class called FileUtil or FileUtils. Hutool’s FileUtil class contains the following types of operations:

  • File operations include creating, deleting, copying, moving, and renaming files and directories
  • File detection: Determines whether a file or directory is non-empty, a directory, a file, etc
  • Absolute path: Convert files in the ClassPath to absolute path files
  • File name: the main file name, the extension is obtained
  • Read operations: including getReader and readXXX
  • Write operations: Include getWriter and writeXXX operations

Classpath, by the way.

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

Put it in the Resources directory of the project structure diagram, and when the project is compiled, it will appear in the Classes directory. The directories on the corresponding disks are as follows:

When reading files, I do not recommend using absolute paths because the file path identifier varies from operating system to operating system. It is best to use relative paths.

TXT file in SRC /resources with the following path parameters:

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

Assuming the file is in the SRC /resources/hutool directory, the path parameter is changed to:

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

05. String tools

StrUtil, the String utility class wrapped in Hutool, is similar to StringUtils in the Apache Commons Lang package, with the advantage that Str is shorter than String, though I don’t think so. However, I do like one of them:

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

06. Reflection tools

Reflection makes Java more flexible, so in some cases reflection can be more effective with less effort. The Hutool ReflectUtil includes:

  • Get constructor
  • For field
  • Get 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;

public class ReflectDemo {
    private int id;

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

    public void print(a) {
        System.out.println("I am the Silent King.");
    }

    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());


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

07. Compression tools

ZipUtil is optimized for the java.util.zip package. It uses a single method to compress and decompress files and directories automatically, eliminating the need for user judgment. 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

Hutool’s IdcardUtil can be used to authenticate id cards, supporting 15-bit and 18-bit ID cards for mainland China and 10-bit ID cards for 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

While a HashMap in Java is strongly typed, Dict wrapped in Hutool is less strict about key types.

Dict dict = Dict.create()
        .set("age".18)
        .set("name"."Silent King II.")
        .set("birthday", DateTime.now());

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

10. Console printing

In the process of local coding, it is often necessary to print the results using system. out, but some complex objects do not support direct printing, such as Arrays. The Console class that Hutool wraps takes a page out of JavaScript’s console.log() and makes printing a very convenient option.

public class ConsoleDemo {
    public static void main(String[] args) {
        // Prints a string
        Console.log("Silent King II, a funny programmer.");

        // Prints the string template
        Console.log("Luoyang was the ancient capital of {} dynasties".13);

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

11. Field validator

When doing Web development, the back end often needs to validate the data submitted from the form. Hutool packaged Validators do a number of valid conditional validations:

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

Validator.isEmail("Silent King II.");
Validator.isMobile("itwanger.com");
Copy the code

12. Bidirectional search for Map

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

BiMap<String, String> biMap = new BiMap<>(new HashMap<>());
biMap.put("wanger"."Silent King II.");
biMap.put("wangsan"."Silent King three.");

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

// get key by value
biMap.getKey("Silent King II.");
biMap.getKey("Silent King three.");
Copy the code

In actual development work, I actually prefer to use Guava’s BiMap over Hutool’s. By the way, I found a mistake in Hutool’s online document and raised an issue (from which I can see that I have a meticulous mind and a pair of clear and bright eyes).

13. Image tools

Hutool’s ImgUtil package can scale, crop, turn to black and white, watermark and more.

Zoom image:

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

Cropped 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"),
        "Silent King II.", Color.WHITE,
        new Font("Black", Font.BOLD, 100),
        0.0.0.8 f
);
Copy the code

This is a chance for everyone to see my brother’s handsome face.

14. Configuration files

As we all know, the widely used Java configuration file Properties has a particularly big complaint: it does not support Chinese. Every time you use it, if you want to store Chinese characters, you have to use IDE plug-ins to convert them to Unicode symbols, and these anti-human symbols are unreadable on the command line.

Thus, the application of Hutool Setting came into being. In addition to compatibility with the Properties file format, Setting also 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:

public class SettingDemo {
    private final static String SETTING = "hutool/example.setting";
    public static void main(String[] args) {
        // Initialize Setting
        Setting setting = new Setting(SETTING);

        / / read
        setting.getStr("name"."Silent King II.");

        // It is automatically loaded when the configuration file changes
        setting.autoLoad(true);

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

15. Log Factory

Hutool’s packaged LogFactory, LogFactory, is compatible with major logging frameworks and is easy to use.

public class LogDemo {
    private static final Log log = LogFactory.get();

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

Logfactory.get () is used to automatically identify the imported Log frame and create a facade Log object of the corresponding Log frame. Then, debug() and info() are called to output logs.

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

StaticLog.info("Oh great {}."."The Writings of the Silent King.");
Copy the code

Cache tools

CacheUtil is a quick cache creation utility class wrapped in Hutool that can create different cache objects:

  • FIFOCache: First in, first out, elements are continuously 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 one.");
fifoCache.put("key2"."Silent King II.");
fifoCache.put("key3"."Silent King three.");
fifoCache.put("key4"."The Silent King iv.");

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

lfuCache.put("key1"."King Of Silence one.");
// Use times +1
lfuCache.get("key1");
lfuCache.put("key2"."Silent King II.");
lfuCache.put("key3"."Silent King three.");
lfuCache.put("key4"."The Silent King iv.");

// since the cache capacity is only 3, the least used element is removed when the fourth element is added (2,3 are removed).
String value2 = lfuCache.get("key2");
String value3 = lfuCache.get("key3");
Copy the code
  • LRUCache determines whether an object is continuously cached based on the time it has been used. When an object is accessed, it is placed in the cache. When the cache is full, the object that has not been used for the longest time is removed.
Cache<String, String> lruCache = CacheUtil.newLRUCache(3);

lruCache.put("key1"."King Of Silence one.");
lruCache.put("key2"."Silent King II.");
lruCache.put("key3"."Silent King three.");
// Use time is near
lruCache.get("key1");
lruCache.put("key4"."The Silent King iv.");

// Since the cache capacity is only 3, the oldest element will be removed when the fourth element is added (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 used, for example, AES and DES
  • Asymmetric encryption, for example, RSA and DSA
  • Digest, for example, MD5, SHA-1, SHA-256, and HMAC

Hutool packages for all three cases:

  • SymmetricCrypto
  • Asymmetrical crypto
  • Digest encrypts Digester

The quick encryption utility class SecureUtil has the following 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:

public class SecureUtilDemo {
    static AES aes = SecureUtil.aes();
    public static void main(String[] args) {
        String encry = aes.encryptHex("Silent King II."); System.out.println(encry); String oo = aes.decryptStr(encry); System.out.println(oo); }}Copy the code

18. Other class libraries

There are many other libraries in Hutool, including MailUtil, QrCodeUtil, EmojiUtil, and EmojiUtil. www.hutool.cn/

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

The Path to Java Programmer advancement, this column is humorous, easy to read, extremely friendly and comfortable for Java enthusiasts 😄, The content includes but is not limited to Java foundation, Java Collection framework, Java IO, Java concurrent programming, Java virtual machine, Java enterprise development (SSM, Spring Boot) and other core knowledge points.

GitHub address: github.com/itwanger/to…

White and dark PDF versions are ready, let’s become better Java engineers together, together!