Hutool -- a small and comprehensive Java tool class library

Posted by gabeanderson on Tue, 08 Feb 2022 15:51:17 +0100

☛ Hutool official website

Include components

A Java basic tool class encapsulates JDK methods such as file, stream, encryption and decryption, transcoding, regularization, thread and XML to form various Util tool classes, and provides the following components:

modularintroduce
hutool-aopJDK dynamic proxy encapsulation provides aspect support under non IOC
hutool-bloomFilterBloom filtering provides bloom filtering of some Hash algorithms
hutool-cacheSimple cache implementation
hutool-coreCore, including Bean operation, date, various utils, etc
hutool-cronThe timed task module provides timed tasks similar to Crontab expressions
hutool-cryptoThe encryption and decryption module provides symmetric, asymmetric and digest algorithm encapsulation
hutool-dbThe data operation after JDBC encapsulation is based on the idea of ActiveRecord
hutool-dfaMulti keyword search based on DFA model
hutool-extraExtension module, encapsulating the third party (template engine, mail, Servlet, QR code, Emoji, FTP, word segmentation, etc.)
hutool-httpHttp client encapsulation based on HttpUrlConnection
hutool-logLog facade for automatic log recognition
hutool-scriptScript execution encapsulation, such as Javascript
hutool-settingMore powerful Setting configuration file and Properties encapsulation
hutool-systemSystem parameter call encapsulation (JVM information, etc.)
hutool-jsonJSON implementation
hutool-captchaImplementation of picture verification code
hutool-poiEncapsulation for Excel and Word in POI
hutool-socketSocket encapsulation of NIO and AIO based on Java

Each module can be introduced separately according to requirements, or all modules can be introduced by introducing hutool all.

Core functions

  • Support generic clone interface and clone class
  • Conversion between types
  • Date time processing
  • IO stream correlation
  • Various tools

Installation – introducing dependencies

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

Examples of common tool classes in projects

Type conversion tool class - Convert

The Convert class can be said to be a tool method class, which encapsulates the conversion of common types in Java to simplify type conversion. Most of the methods in the Convert class are toXXX, and the parameter is Object, which can Convert any possible type to the specified type. At the same time, the second parameter defaultValue is supported, which is used to return a default value when the conversion fails.

  1. Convert to string

    int a = 1;
    // aStr is 1
    String aStr = Convert.toStr(a);
    
    long[] b = {1,2,3,4,5};
    // bStr is: "[1, 2, 3, 4, 5]"
    String bStr = Convert.toStr(b);
    
  2. Converts to an array of the specified type

    String[] b = { "1", "2", "3", "4" };
    //The result is an Integer array
    Integer[] intArray = Convert.toIntArray(b);
    
    long[] c = {1,2,3,4,5};
    //The result is an Integer array
    Integer[] intArray2 = Convert.toIntArray(c);
    
  3. Convert to date object

    String a = "2021-05-06";
    Date value = Convert.toDate(a);
    
  4. Convert to collection

    Object[] a = {"a", "you", "good", "", 1};
    List<?> list = Convert.convert(List.class, a);
    //This can be used from 4.1.11
    List<?> list = Convert.toList(a);
    
Datetime tool - DateUtil

It is mainly the conversion between date and string, and provides the positioning of date (a month ago, etc.).

  1. Conversion between Date, long and Calendar

    //current time 
    Date date = DateUtil.date();
    //current time 
    Date date2 = DateUtil.date(Calendar.getInstance());
    //current time 
    Date date3 = DateUtil.date(System.currentTimeMillis());
    //Current time string, format: yyyy MM DD HH: mm: SS
    String now = DateUtil.now();
    //Current date string, format: yyyy MM DD
    String today= DateUtil.today();
    
  2. String to date

    /**
    * DateUtil.parse The method will automatically recognize some common formats, including:
    
    * yyyy-MM-dd HH:mm:ss
    * yyyy-MM-dd
    * HH:mm:ss
    * yyyy-MM-dd HH:mm
    * yyyy-MM-dd HH:mm:ss.SSS
    */
    String dateStr = "2021-05-01";
    Date date = DateUtil.parse(dateStr);
    
    //We can also use custom date format conversion:
    String dateStr = "2021-05-01";
    Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
    
  3. Format date output

    String dateStr = "2021-05-01";
    Date date = DateUtil.parse(dateStr);
    
    //Result 2021 / 05 / 01
    String format = DateUtil.format(date, "yyyy/MM/dd");
    
    //Formatting of common formats, result: 2021-05-01
    String formatDate = DateUtil.formatDate(date);
    
    //Result: 2021-05-01 00:00:00
    String formatDateTime = DateUtil.formatDateTime(date);
    
    //Result: 00:00:00
    String formatTime = DateUtil.formatTime(date);
    
  4. Gets a part of a Date object

    Date date = DateUtil.date();
    //Get part of the year
    DateUtil.year(date);
    //Get the month, counting from 0
    DateUtil.month(date);
    //Get month enumeration
    DateUtil.monthEnum(date);
    //.....
    
  5. Start and end time

    String dateStr = "2021-05-01 22:33:23";
    Date date = DateUtil.parse(dateStr);
    
    //The beginning of the day, result: 2021-05-01 00:00:00
    Date beginOfDay = DateUtil.beginOfDay(date);
    
    //The end of the day, result: 2021-05-01 23:59:59
    Date endOfDay = DateUtil.endOfDay(date);
    
  6. Date time offset

    String dateStr = "2021-05-01 22:33:23";
    Date date = DateUtil.parse(dateStr);
    
    //Result: 2021-05-03 22:33:23
    Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
    
    //Common offset, result: 2021-05-04 22:33:23
    DateTime newDate2 = DateUtil.offsetDay(date, 3);
    
    //Common offset, result: 2021-05-01 19:33:23
    DateTime newDate3 = DateUtil.offsetHour(date, -3);
    

    For the current time, a simplified offset method is provided (such as yesterday, last week, last month, etc.).

    //yesterday
    DateUtil.yesterday()
    //tomorrow
    DateUtil.tomorrow()
    //last week
    DateUtil.lastWeek()
    //next week
    DateUtil.nextWeek()
    //last month
    DateUtil.lastMonth()
    //next month
    DateUtil.nextMonth()
    
  7. Date time difference

    Sometimes we need to calculate the time difference between two dates (days, hours, etc.). Hutool encapsulates this method as the between method.

    String dateStr1 = "2021-05-01 22:33:23";
    Date date1 = DateUtil.parse(dateStr1);
    
    String dateStr2 = "2021-05-01 23:33:23";
    Date date2 = DateUtil.parse(dateStr2);
    
    //One month, 31 days
    long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
    
  8. Format time difference

    Sometimes we want to see a readable time difference, such as XX days, XX hours, XX minutes and XX seconds. At this time, use dateutil Formatbetween method.

    //Level.MINUTE means accurate to minutes
    String formatBetween = DateUtil.formatBetween(between, Level.MINUTE);
    //Output: 31 days and 1 hour
    Console.log(formatBetween);
    
  9. timer

    Timers are used to calculate the time spent on a piece of code or process.

    TimeInterval timer = DateUtil.timer();
    
    //---------------------------------
    //-------This is the execution process
    //---------------------------------
    
    timer.interval();//Milliseconds spent
    timer.intervalRestart();//Reset time, and return time
    timer.intervalMinute();//Minutes spent
    
  10. Constellation and zodiac

    // Capricorn
    String zodiac = DateUtil.getZodiac(Month.JANUARY.getValue(), 19);
    
    // "Dog"
    String chineseZodiac = DateUtil.getChineseZodiac(1994);
    
  11. other

    //Age
    DateUtil.ageOfNow("1990-01-30");
    
    //Leap year
    DateUtil.isLeapYear(2017);
    
DateTime object - DateTime
  1. New object

    DateTime object contains many construction methods. The parameters supported by the construction method are:

    • Date
    • Calendar
    • String (date string, the second parameter is date format)
    • long milliseconds

    There are two ways to build objects: datetime Of() and new DateTime().

    Date date = new Date();
            
    //Create in new mode
    DateTime time = new DateTime(date);
    Console.log(time);
    
    //of mode creation
    DateTime now = DateTime.now();
    DateTime dt = DateTime.of(date);
    
  2. Use object

    DateTime dateTime = new DateTime("2021-05-01 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
            
    //Year, result: 2021
    int year = dateTime.year();
    
    //Non season, results: SUMMER
    Season season = dateTime.seasonEnum();
    
    //Month, result: month May
    Month month = dateTime.monthEnum();
    
    //Day, result: 1
    int day = dateTime.dayOfMonth();
    
  3. Variability of objects

    The DateTime object is a variable object by default (the offset, setField and setTime methods are called to change itself by default), but this variability sometimes causes many problems (for example, multiple places share a DateTime object). We can call the setMutable(false) method to make it an immutable object. In immutable mode, the offset and setField methods return a new object, and the setTime method throws an exception.

    DateTime dateTime = new DateTime("2021-05-01 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
    
    //By default, DateTime is a variable object. In this case, offset == dateTime
    DateTime offset = dateTime.offset(DateField.YEAR, 0);
    
    //After it is set as immutable object, the change will return to the new object. At this time, offset= dateTime
    dateTime.setMutable(false);
    offset = dateTime.offset(DateField.YEAR, 0);
    
  4. Format as string

    Call toString() method to return a string in the format of yyyy MM DD HH: mm: SS. Call toString(String format) to return a string in the specified format.

    DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
    //Result: 2021-05-01 12:34:23
    String dateStr = dateTime.toString();
    
    //Result: May 1, 2021
    
String tool StrUtil
  1. hasBlank,hasEmpty

    The difference between the two methods is that hasEmpty only judges whether it is null or empty string (""), while hasBlank will also short invisible characters. isEmpty is the same as isBlank.

  2. removePrefix,removeSuffix

    These two remove the prefix and suffix of the string, such as the extension of a file name.

    String fileName = StrUtil.removeSuffix("pretty_girl.jpg", ".jpg")  //fileName -> pretty_girl
    
  3. sub method

    String str = "abcdefgh";
    String strSub1 = StrUtil.sub(str, 2, 3); //strSub1 -> c
    String strSub2 = StrUtil.sub(str, 2, -3); //strSub2 -> cde
    String strSub3 = StrUtil.sub(str, 3, 2); //strSub2 -> c
    
  4. format method

    String template = "{}love{},Like a mouse loves rice";
    String str = StrUtil.format(template, "I", "you"); //STR - > I love you like a mouse loves rice
    
Digital tool - NumberUtil
  1. add , subtract , multiply and divide

    • NumberUtil.add adds a number type
    • NumberUtil.sub subtracts for numeric types
    • NumberUtil.mul multiplies for numeric types
    • NumberUtil.div performs division for numeric types and provides overloaded methods to specify the number of decimal places to be retained and the method of discarding in case of inexhaustible division.

    The above four operations will be calculated after double is converted to BigDecimal, which solves the problem that float and double types cannot be calculated accurately. These methods are commonly used in Business Computing.

  2. Keep decimal

    • NumberUtil. The round method mainly encapsulates the methods in BigDecimal to retain decimals and return BigDecimal. This method is more flexible. You can choose to round or discard all.
    • NumberUtil. The roundstr method mainly encapsulates string Format method, the discarding method is rounded.
    double te1=123456.123456;
    double te2=123456.128456;
    Console.log(round(te1,4));//Result: 123456.1235
    Console.log(round(te2,4));//Result: 123456.1285
    
    double te1=123456.123456;
    double te2=123456.128456;
    Console.log(roundStr(te1,2));//Result: 123456.12
    Console.log(roundStr(te2,2));//Result: 123456.13
    
  3. decimalFormat

    long c=299792458;//light speed
    String format = NumberUtil.decimalFormat(",###", c);//299,792,458
    

    In the format, the number length is mainly specified by # and 0 placeholders. 0 indicates that if the number of digits is insufficient, it will be filled with 0, # indicating that the number will be pulled to this position whenever possible.

    • 0 - > take one digit integer.

    • 0.00 - > take one integer and two decimal places.

    • 00.000 - > take two integers and three decimals.

    • #- > take all integer parts.

    • #. ##% - > count as a percentage and take two decimal places.

    • #. #######e0 - > display as scientific counting method with five decimal places.

    • , ### - > every three digits are separated by commas, for example: 299792458.

    • Speed of light is per second, #### meters - > embed format into text.

  4. Is it a number

    • NumberUtil. Is isnumber a number

    • NumberUtil. Is isinteger an integer

    • NumberUtil. Is isdouble a floating point number

    • NumberUtil. Is isprimes a prime number

  5. random number

    • NumberUtil.generateRandomNumber generates a non repeating random number. According to the given minimum number, maximum number and the number of random numbers, a specified non repeating array is generated.

    • NumberUtil.generateBySet generates non repeating random numbers. According to the given minimum number, maximum number and the number of random numbers, the specified non repeating array is generated.

  6. other

    • NumberUtil.factorial factorial

    • NumberUtil. Square root of sqrt

    • NumberUtil. Maximum common divisor

    • NumberUtil.multiple least common multiple

    • NumberUtil.getBinaryStr gets the binary string corresponding to the number

    • NumberUtil.binaryToInt binary to int

    • NumberUtil.binaryToLong binary to long

    • NumberUtil.compare compares the size of two values

    • NumberUtil.toStr number to string, automatically and remove the extra 0 after the trailing decimal point

Random tool RandomUtil
  • RandomUtil.randomInt gets the random number within the specified range

  • RandomUtil. Random bytes

  • RandomUtil. Element in random list

  • RandomUtil.randomEleSet randomly obtains a certain number of non repeating elements in the list and returns Set

  • RandomUtil.randomString gets a random string (containing only numbers and characters)

  • RandomUtil.randomNumbers gets a string that contains only numbers

  • RandomUtil. Random UUID random UUID

  • RandomUtil.weightRandom weight random generator, pass in the weighted object, and then randomly obtain the object according to the weight

Unique ID tool - IdUtil
  1. UUID

    The full name of UUID is universal unique identifier, and JDK passes Java util. UUID provides encapsulation of leach Salz variants. In Hutool, generate a UUID string as follows:

    //The generated UUID is a string with -, similar to a5c8a5e8-df2b-4706-bea4-08d0939410e3
    String uuid = IdUtil.randomUUID();
    
    //The generated string is a string without -, similar to b17f24ff026d40949c85a24f4f375d42
    String simpleUUID = IdUtil.simpleUUID();
    

    Description Hutool rewrites Java util. The logic of UUID, corresponding to CN Hutool. core. Lang.uuid, so that the generation of UUID string without - does not need character replacement, and the performance is about doubled.

  2. ObjectId

    ObjectId is a unique ID generation strategy of MongoDB database and a variant of UUID version1.

    //Generation similar: 5b9e306a4df4f8c54a39fb0c
    String id = ObjectId.next();
    
    //Method 2: starting from Hutool-4.1.14
    String id2 = IdUtil.objectId();
    
  3. Snowflake

    In distributed systems, there are some scenarios that need to use a globally unique ID. sometimes we want to use a simpler ID and hope that the ID can be generated in an orderly manner according to time. Twitter's Snowflake algorithm is such a generator.

    //Parameter 1 is the terminal ID
    //Parameter 2 is the data center ID
    Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    long id = snowflake.nextId();
    
CSV file processing tool - CsvUtil
  1. Read as CsvRow

    CsvReader reader = CsvUtil.getReader();
    //Read CSV data from file
    CsvData data = reader.read(FileUtil.file("test.csv"));
    List<CsvRow> rows = data.getRows();
    //Traversal row
    for (CsvRow csvRow : rows) {
        //getRawList returns a List. Each item in the List is a cell in CSV (i.e. comma separated part)
        Console.log(csvRow.getRawList());
    }
    
  2. Read as Bean list

    1. CSV to be tested first: test_bean.csv
    full name,gender,focus,age
     Zhang San,male,nothing,33
     Li Si,male,Good object,23
     Mei Mei Wang,female,Special attention,22
    
    1. Define Bean

      // lombok annotation
      @Data
      private static class TestBean{
          // If the title in the csv does not correspond to the field, you can use the alias annotation to set the alias
          @Alias("full name")
          private String name;
          private String gender;
          private String focus;
          private Integer age;
      }
      
    2. read

      final CsvReader reader = CsvUtil.getReader();
      // Suppose the csv file is in the classpath directory
      final List<TestBean> result = reader.read(
                      ResourceUtil.getUtf8Reader("test_bean.csv"), TestBean.class);
      
    3. output

      CsvReaderTest.TestBean(name=Zhang San, gender=male, focus=nothing, age=33)
      CsvReaderTest.TestBean(name=Li Si, gender=male, focus=Good object, age=23)
      CsvReaderTest.TestBean(name=Mei Mei Wang, gender=female, focus=Special attention, age=22)
      
  3. Generate CSV file

    //Specify path and encoding
    CsvWriter writer = CsvUtil.getWriter("e:/testWrite.csv", CharsetUtil.CHARSET_UTF_8);
    //Write by line
    writer.write(
        new String[] {"a1", "b1", "c1"}, 
        new String[] {"a2", "b2", "c2"}, 
        new String[] {"a3", "b3", "c3"}
    );
    

Map tool - MapUtil
  1. join method

This method is still very common to convert a collection into a string. It is strutil Inverse method of split. The parameters of this method support the collection of various types of objects. Finally, when each object is connected, its toString() method is called.

String[] col= new String[]{"a","b","c","d","e"};
List<String> colList = CollUtil.newArrayList(col);

String str = CollUtil.join(colList, "#"); //str -> a#b#c#d#e

  1. newHashMap, newHashSet, newArrayList methods

These methods are to create corresponding data structures. The type of data structure elements depends on the type of your variables.

HashMap<String, String> map = CollUtil.newHashMap();
HashSet<String> set = CollUtil.newHashSet();
ArrayList<String> list = CollUtil.newArrayList();
  1. filter method

This method can filter the map and exclude unnecessary key s.

@Test
public void CollUtil_Filter() {
    Map<String, Object> m = new HashMap<String, Object>() {{
        put("k1", "v1");
        put("k2", "v2");
        put("k3", "v3");
    }};
    String[] inc = {"k1", "k3"};//Required key
    List<String> incList = Arrays.asList(inc);
    m = CollectionUtil.filter(m, new Editor<Map.Entry<String, Object>>() {
        @Override
        public Map.Entry<String, Object> edit(Map.Entry<String, Object> stringObjectEntry) {
            if (incList.contains(stringObjectEntry.getKey())) {
                return stringObjectEntry;
            }
            return null;
        }
    });
    log.info("{}", m);
}

result:{k3=v3, k1=v1}

Topics: Java