I like an open source class library, which can help you simplify each line of code and recommend it to you


A small partner in the “black iron age” reader group sighed, “hutool‘s open source class library is too powerful. Basically, there should be tool classes in it.” Seriously, I often use hutool at work. It can really help us simplify every line of code, make Java as elegant as a functional language, and make the Java language “sweet”.

However, some small partners in the group said they didn’t know the open source class library. They heard it for the first time. So I decided to write an article to popularize it. After all, good wheels are worth recommending.

The author of hutool said on the official website that hutool is a self-made word of Hu + tool (it seems that we can guess it needless to say), “Hu” is used to pay tribute to his “predecessor” company, “tool” means tool, and the homonym is interesting, “confused”, which implies the pursuit of “all things are confused, no loss, no gain” (an open-source Class Library), Up to the height of philosophy, the author is great.

After looking at the introduction of a member of the development team, the author of a Java back-end tool actually loves the front-end, digital and beautiful women. Uh huh, it’s really “hard to be confused” (manual dog head).

Even the pr (pull request) specification submitted to this open source class library is very “pathological” (HA HA):

That’s all the nonsense. Come on, let’s go!

01. Introduce hutool

The Maven project only needs to add the following dependencies in the pom.xml file.

<dependency>    <groupId>cn.hutoolgroupId>    <artifactId>hutool-allartifactId>    <version>5.4.3version>dependency>

The design idea of hutool is to minimize repeated definitions and minimize util packages in the project. A good wheel can avoid “copy and paste” to a great extent, thus saving our developers the packaging time of public class libraries and public tool methods in the project. At the same time, mature open source libraries can also avoid bugs caused by imperfect encapsulation to the greatest extent.

As the author said on his official website:

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

After having hutool, introduce hutool – > directSecureUtil.md5()

Hutool not only encapsulates files, streams, encryption and decryption, transcoding, regularization, threads and XML at the bottom of JDK, but also provides the following components:

Very many, very comprehensive. In view of this, I only choose some I like to introduce (secretly tell you, I just want to be lazy).

02. Type conversion

Type conversion is very common in java development, especially when obtaining parameters from httprequest. The front end passes an integer, but the back end can only obtain the string first and then call itparseXXX()Method conversion, coupled with blank judgment, is very cumbersome.

Hutool’s convert class can simplify this operation, convert any possible type to the specified type, and the second parameter DefaultValue can be used to return a default value when the conversion fails.

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

Convert string to date:

String   dateStr  = " September 29, 2020 "; Date   date  =  Convert.toDate(dateStr);

Convert string to unicode:

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

03. Date and time

The date and calendar provided by JDK are not easy to use. The dateutil encapsulated by hutool is much more comfortable to use!

Get current date:

Date date = DateUtil.date();

DateUtil.date()The returned is actually datetime, which inherits from the date object and overrides thetoString()Method, returnyyyy-MM-dd HH:mm:ssFormat string.

Do some friends want to see the time when I wrote this article and output it to you:

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

String to date:

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

DateUtil.parse()It will automatically recognize 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

You can also recognize Chinese:

  • Mm / DD / yyyy H / min / S

Format time difference:

String   dateStr1  = " 2020-09-29   22:33:23"; Date   date1  =  DateUtil.parse(dateStr1); String   dateStr2  = " 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);

Constellations and signs:

//   Sagittarius string   zodiac  =  DateUtil.getZodiac(Month.DECEMBER.getValue(),   10);//   Snake string   chineseZodiac  =  DateUtil.getChineseZodiac(1989);

04. IO flow related

IO operations include read and write. Application scenarios mainly include network operations and file operations. The native Java class library distinguishes between character stream and byte stream. There are many kinds of byte streams InputStream and OutputStream, which make people feel numb when used.

Hutool encapsulates the stream operation tool class ioutil, file read-write operation tool class fileutil, file type judgment tool class filetypeutil, etc.

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

In IO operations, file operations are relatively complex, but they are also used frequently. Almost all projects have a tool class called fileutil or FileUtils. The fileutil class of hutool contains the following operations:

  • File operations: including creating, deleting, copying, moving and renaming file directories
  • File judgment: judge whether the file or directory is not empty, whether it is a directory, whether it is a file, etc
  • Absolute path: convert files in classpath to absolute path files
  • File name: the main file name and extension
  • Read operations: including getReader and readxxx operations
  • Write operations: including 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, pictures, etc. where are these files usually placed?

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

When we want to read a file, I do not recommend using an absolute path, because if the operating system is different, the path identifier of the file is also different. It is best to use relative paths.

Suppose insrc/resourcesA file origin.txt is placed. The path parameters of the file are as follows:


Suppose the file is placed insrc/resources/hutoolDirectory, the path parameter is changed to:


05. String tool

The string tool class strutil encapsulated by hutool is similar to stringutils in Apache commons Lang package. The author believes that the advantage is that STR is shorter than string, although I don’t think so. However, I like one of them:

String   template  = "{}, A silent 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 is a silent but interesting programmer. If you like his article, please search silent Wang Er on wechat

06. Reflection tool

Reflection mechanism can make Java more flexible, so in some cases, reflection can achieve twice the result with half the effort. The reflection tool reflectutil encapsulated by hutool includes:

  • Get construction method
  • Get field
  • Get field value
  • Acquisition 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;/**  * @ author   Search "silent King 2" on wechat and reply to keywords   PDF  */ public   class   ReflectDemo  {     private   int   id;      public   ReflectDemo()  {         System.out.println ("construction method");     }     public   void   print()  {         System. Out. Println ("I'm the second silent king");     }     public   static   void   main(String[]   args)   throws   IllegalAccessException  {        //  Build object          ReflectDemo   reflectDemo  =  ReflectUtil.newInstance(ReflectDemo.class);         //  Get construction method          Constructor[]   constructors  =  ReflectUtil.getConstructors(ReflectDemo.class);          for  ( Constructor   constructor  :  constructors)  {             System.out.println(constructor.getName());         }        //  Get field          Field   field  =  ReflectUtil.getField(ReflectDemo.class,  " id");          field.setInt(reflectDemo,   10);         //  Get 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());         }        //  Gets the specified method          Method   method  =  ReflectUtil.getMethod(ReflectDemo.class,  " print");          System.out.println(method.getName());         //  Execution method          ReflectUtil.invoke(reflectDemo,  " print");     }}

07. Compression tools

In Java, packaging and compressing files and folders is a very cumbersome thing. Ziputil encapsulated by hutool is optimized for java.util.zip package. You can use one method to solve the compression and decompression, and automatically deal with the problems of files and directories. It no longer needs user judgment, which greatly simplifies the complexity of compression and decompression.

ZipUtil.zip("hutool", "hutool.zip");File unzip = ZipUtil.unzip("hutool.zip", "hutoolzip");

08. ID card tools

The idcardutil encapsulated by hutool can be used to verify identity cards, supporting 15 bit and 18 Bit identity cards in the mainland and 10 bit identity 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);

Hash09, HashMap extension

HashMap in Java is strongly typed, while dict encapsulated by hutool has less strict requirements on 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");

10. Console printing

It is often used in the process of local codingSystem.outPrint results, but often some complex objects do not support direct printing, such as arrays, which need to be calledArrays.toString。 The console class encapsulated by hutool draws lessons from JavaScriptconsole.log(), making printing a very convenient way.

/**  * @ author   Search "silent King 2" on wechat and reply to keywords   PDF  */ public   class   ConsoleDemo  {     public   static   void   main(String[]   args)  {        //  Print string          Console.log ("silent King II, an interesting programmer");         //  Print string template          Console.log ("Luoyang is the ancient capital of {} Dynasty", 13);          int  []  ints  = { 1,2,3,4};         //  Print array          Console.log(ints);     }}

11. Field Validator

When doing web development, the back end usually needs to verify the data submitted by the form. The validator encapsulated by hutool can perform many valid condition verifications:

  • Is it a mailbox
  • Is it IP V4 or V6
  • Is it a phone number
  • wait
Validator.isemail ("silent King 2"); Validator.isMobile("itwanger.com");

12. Bidirectional lookup map

Guava provides a special map structure called bimap, which realizes a two-way search function. You can find value according to key or key according to value. Hutool also provides this map structure.

BiMap   biMap  =  new   BiMap<>(new   HashMap<>()); biMap.put("wanger",  " Silent King II "); biMap.put("wangsan",  " King of silence three ")//   get   value   by   keybiMap.get("wanger"); biMap.get("wangsan");//   get   key   by   Valuebimap.getkey ("silent King 2"); Bimap.getkey ("silent king 3");

In actual development, I prefer guava’s bimap to hutool’s. Here, I found an error in hutool’s online document and raised an issue (from which I can see my meticulous heart and clear and bright eyes).

13. Picture tools

Imgutil encapsulated by hutool can zoom, crop, convert to black and white, add water and print pictures.

Zoom picture:

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

Crop picture:

ImgUtil.cut(        FileUtil.file("hutool/wangsan.jpg"),        FileUtil.file("hutool/wangsan_cut.jpg"),        new Rectangle(200, 200, 100, 100));

Add watermark:

ImgUtil.pressText(//          FileUtil.file("hutool/wangsan.jpg"),          FileUtil.file("hutool/wangsan_ logo.jpg"),         " Silent King II ",   Color.WHITE,          new   Font ("bold",   Font.BOLD,   100),          0          0          0.8f);

Let’s take the opportunity to enjoy the handsome face of the second brother.

14. Configuration file

As we all know, the widely used configuration file properties in Java has a particularly big criticism: it does not support Chinese. Every time you use it, if you want to store Chinese characters, you must use ide related plug-ins to convert them to unicode symbols, and this anti-human symbol can’t be seen at all on the command line.

Therefore, hutool’s setting was used. In addition to being compatible with the properties file format, setting also provides some unique functions, including:

  • Support for various coding methods
  • Variable support
  • Grouping support

Start with the entire configuration file example.setting, as follows:

Name = silent King II age = 18

Then read and update the configuration file:

/**  * @ author   Search "silent King 2" on wechat and reply to keywords   PDF  */ public   class   SettingDemo  {     private   final   static   String   SETTING  = " hutool/example.setting";      public   static   void   main(String[]   args)  {        //  initialization   Setting          Setting   setting  =  new   Setting(SETTING);         //  read          setting.getStr("name",  " Silent King II ");         //  Automatically load when profile changes          setting.autoLoad(true);         //  Add key value pairs by code          setting.set("birthday",  " September 29, 2020 ");          setting.store(SETTING);     }}

15. Log factory

The log factory encapsulated by hutool is compatible with major log frameworks and is very easy to use.

/**  * @ author   Search "silent King 2" on wechat and reply to keywords   PDF  */ public   class   LogDemo  {     private   static   final   Log   log  =  LogFactory.get();      public   static   void   main(String[]   args)  {         Log.debug ("it's hard to be confused");     }}

First passLogFactory.get()Automatically introduce the log framework introduced to create the corresponding Log object of the log framework, then call it.debug()info()And so on.

If you don’t want to create a log object, you can use staticlog. As the name suggests, a log class that provides static methods.

Staticlog. Info ("cool  {}.", " Silent Wang Er's article ");

16. Cache tool

Cacheutil is a cache creation shortcut class encapsulated by hutool, which 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 cleaned up. If it is still full after cleaning, the first in cache is deleted.
Cache   fifoCache  =  CacheUtil.newFIFOCache(3); fifoCache.put("key1",  " Silent King I "); fifoCache.put("key2",  " Silent King II "); fifoCache.put("key3",  " King of silence three "); fifoCache.put("key4",  " Silent king four ")//   Size   So, 3   key3   After putting   key1   Cleared string   value1  =  fifoCache.get("key1");
  • Lfucache, least used, determines whether the object is continuously cached according to the number of times used. When the cache is full, the expired objects are cleaned up. If the cache is still full after cleaning, the least accessed objects are cleared, and the number of accesses to other objects is subtracted from the minimum number of accesses, so that new objects can be counted fairly after entering.
Cache   lfuCache  =  CacheUtil.newLFUCache(3); lfuCache.put("key1",  " Silent King I ")//   Usage times + 1lfucache.get ("key1"); lfuCache.put("key2",  " Silent King II "); lfuCache.put("key3",  " King of silence three "); lfuCache.put("key4",  " Silent king four ")//   Because the cache capacity is only   3. When the second paragraph is added   four   When there are two elements, the least used will be removed (2,3 will be removed) string   value2  =  lfuCache.get("key2"); String   value3  =  lfuCache.get("key3");
  • Lrucache, which has not been used for the longest time recently, determines whether the object is continuously cached according to the use time. When the object is accessed, it is put into the cache. When the cache is full, the object that has not been used for the longest time will be removed.
Cache   lruCache  =  CacheUtil.newLRUCache(3); lruCache.put("key1",  " Silent King I "); lruCache.put("key2",  " Silent King II "); lruCache.put("key3",  " King of silence three ")//   Lrucache. Get ("key1") has been used for a long time; lruCache.put("key4",  " Silent king four ")//   Because the cache capacity is only   3. When the second paragraph is added   four   When there are two elements, the longest used will be removed (2) string   value2  =  lruCache.get("key2"); System.out.println(value2);

17. Encryption and decryption

There are three types of encryption:

  • Symmetric encryption, such as AES, DES, etc
  • Asymmetric encryption, such as RSA, DSA, etc
  • Digest, such as MD5, SHA-1, SHA-256, HMAC, etc

Hutool encapsulates these three situations:

  • Symmetric crypto
  • Asymmetric encryption asymmetriccrypto
  • Digest encryption

The fast encryption tool class securecutil 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:

/**  * @ author   Search "silent King 2" on wechat and reply to keywords   PDF  */ 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);     }}

18. Other class libraries

There are many class libraries in hutool, especially some further encapsulation of third-party class libraries, such as mailutil, QR code tool qrcodeutil, Emoji tool emojiutil. Partners can refer to the official documents of hutool: https://www.hutool.cn/

Project source code address:https://github.com/looly/hutool

PS: if you need a java book list, I’ll be thereGitHubA treasure project was found on the, and the list of books in it can be described as everything. You can get your own partners on demand, and the address is as follows:


Finally, ask for a daily praise. I’ll do it first for respect. You can do it at will

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]