This is the 30th day of my participation in the August Text Challenge.More challenges in August

Introduction to the

Hutool is a small and complete Java tool class library, through the static method encapsulation, reduce the cost of learning related API, improve work efficiency, make Java has the elegant functional language, let the Java language can also be “sweet”.

The tools and methods in Hutool come from the elaboration of each user. It covers all aspects of the underlying code of Java development. It is not only a sharp tool to solve small problems in large project development, but also an efficiency responsibility in small projects.

Hutool is a friendly alternative to the util package in a project. It saves developers the time to encapsulate common classes and common tool methods in a project, enables development to focus on the business, and avoids bugs caused by incomplete encapsulation to the maximum.

This is the official introduction to it, simply put, it through some encapsulation, the original slightly complex API further optimization, so that you can use more convenient, of course, the syntax will be easier to understand than the original.

Contains the components

Util utility class a Java basic utility class that encapsulates JDK methods such as files, streams, encryption and decryption, transcoding, re, threads, and XML. Util utility classes provide the following components:

The module introduce
hutool-aop JDK dynamic proxy encapsulation, providing non-IOC aspect support
hutool-bloomFilter Bloom filtering, which provides some Hash algorithms for Bloom filtering
hutool-cache Simple cache implementation
hutool-core Core, including Bean operations, dates, various utils, and so on
hutool-cron Scheduled task module that provides scheduled tasks like Crontab expressions
hutool-crypto Encryption and decryption module, providing symmetric, asymmetric and digest algorithm encapsulation
hutool-db JDBC encapsulated data manipulation, based on ActiveRecord ideas
hutool-dfa Multi-keyword search based on DFA model
hutool-extra Extension module, encapsulation for third parties (template engine, mail, Servlet, TWO-DIMENSIONAL code, Emoji, FTP, word segmentation, etc.)
hutool-http Http client encapsulation based on HttpUrlConnection
hutool-log Automatic identification of log facade of log implementation
hutool-script Scripts perform encapsulation, such as Javascript
hutool-setting More powerful Setting profile and Properties wrapper
hutool-system System parameters call encapsulation (JVM information, etc.)
hutool-json JSON implementation
hutool-captcha Image verification code implementation
hutool-poi Excel encapsulation in POI
hutool-socket NIO and AIO Socket encapsulation based on Java

Each module can be imported individually as required, or all modules can be imported by hutool-all.

The installation

1. Maven Project

Add the following to the project’s PM.xml dependencies:

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

2. Non-maven projects

Download address: https://repo1.maven.org/maven2/cn/hutool/hutool-all/5.0.7/

Download hutool -all-x.x.x. jar.

Here’s a primer on the use of some components.

Type conversion

1, common type conversion

In traditional type conversions, we use the valueof() method that wraps the class, for example:

String s = "1234";
int num = Integer.valueOf(s);
double d = Double.valueOf(s);
float f = Float.valueOf(s);
Copy the code

But obviously the actual situation is not so simple, in enterprise development projects, from the front end of the various parameters, a variety of types, how do we know the parameter type and make the corresponding conversion? All parameters are cast to String first, as in the Web HttpServletRequest getParamer() method, which always returns String. To convert a parameter to a String and then to the corresponding data type, you also need to consider conversion exceptions, so you usually need to use a try-catch outside of the conversion code.

To make the conversion process easier, HuTool provides a type conversion tool called Convert.

Let’s see how to Convert using Convert:

String s = "1234";
int num = Convert.toInt(s);
double d = Convert.toDouble(s);
float f = Convert.toFloat(s);
Copy the code

First, in terms of code style, Convert is unified by using the Convert class as a utility class for type conversion, rather than using a wrapper class for each type.

Of course, the Convert class does much more than that, such as:

String[] s = { "1"."2"."3"."4"."5" };
Integer[] intArray = Convert.toIntArray(s);
Double[] doubleArray = Convert.toDoubleArray(s);
Float[] floatArray = Convert.toFloatArray(s);
Character[] charArray = Convert.toCharArray(s);
Copy the code

Convert an array to an arbitrary type.

For collections, Convert also supports conversions:

Object[] objs= {"hello"."world"."java".1}; List<? > list = Convert.toList(objs);Copy the code

And date types:

String s = "2019-12-07";
Date date = Convert.toDate(s);
Copy the code

HuTool provides a special tool class for handling dates, which we’ll cover later.

2. Other type conversions

Convert () ¶ Convert () ¶ Convert () ¶ Convert () ¶

String s = "1234";
int num = Convert.convert(Integer.class, s);
double d = Convert.convert(Double.class, s);
float f = Convert.convert(Float.class, s);
Copy the code

The convert() method allows you to convert any type to a specified type, but this method is ultimately limited. How do we convert an array to a List?

We can use an overloaded method convert(TypeReference Reference, Object Value), which requires a TypeReference Object parameter, We can create a TypeReference object and use nested generics to specify the type to be converted, for example:

Object[] objs = { "hello"."world"."java"};
List<String> list = Convert.convert(new TypeReference<List<String>>() {}, objs);
Copy the code

Convert also provides conversion between full-angle and half-angle symbols, such as:

// Convert full-angle characters to half-angle characters
String s = "1,2,3,4,5";
String dbc = Convert.toDBC(s);
// Convert a half Angle character to a full Angle character
String sbc = Convert.toSBC(dbc);
Copy the code

To get a more intuitive view of the results:

3. Coding conversion

In some scenarios, such as form submission, the parameters are simply encrypted, and the hexadecimal conversion is usually used. Of course, we do not write the hexadecimal conversion ourselves, we always go to Baidu to find a ready-made one. However, this is not necessary with HuTool, which provides methods to do hexadecimal conversion.

String s = Hello world.;
// Converts to a hexadecimal string
String hex = Convert.toHex(s, CharsetUtil.CHARSET_UTF_8);
// Convert to a normal string
String str = Convert.hexToStr(hex, CharsetUtil.CHARSET_UTF_8);
Copy the code

Running results:

E4bda0e5a5bde4b896e7958c Hello worldCopy the code

Note that the encoding objects must be the same. Utf-8 encoding is used here, so the conversion process is successful. If the encoding is different, garbled characters will appear when converting to ordinary strings.

There is also Unicode encoding and string conversion:

String s = Hello world.;
// Convert to Unicode encoding
String unicode = Convert.strToUnicode(s);
// Convert to a normal string
String str = Convert.unicodeToStr(unicode);
Copy the code

Running results:

\ u4F60 \ U597d \ U4E16 \u754c Hello worldCopy the code

The Convert class also provides convertCharset () for converting a string to a specified encoding, such as when dealing with form data, which is often garbled, as follows:

String s = Hello world.;
// Convert the string to garbled characters first
String str = Convert.convertCharset(s, CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1);
// Handle garbled characters
String result = Convert.convertCharset(str, CharsetUtil.ISO_8859_1, CharsetUtil.UTF_8);
Copy the code

Running results:

???????????????????? HELLO WORLDCopy the code

There is also the function of the amount of case conversion:

double money = 2019.127;
String s = Convert.digitToChinese(money);
Copy the code

Running results:

Twenty-one nine dollars and thirteen centsCopy the code

4. Custom type conversion

Isn’t the Convert class very powerful? Moving on, it’s definitely not possible to include all data types for conversions because of Java’s object-oriented nature, but HuTool provides custom conversions.

ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
converterRegistry.putCustom(Person.class, CustomConverter.class);
String[] str = { "20"."Zhang" };
Person person = converterRegistry.convert(Person.class, str);
System.out.println(person);
Copy the code

Running results:

Person [age=20, name= Zhang SAN]Copy the code

How does this converter convert an array type to a Person object? (In three steps)

  1. A custom class implements the Converter interface and overwrites the convert() method
  2. Register custom converters
  3. Realize the transformation

Define a Person class:

public class Person {

	private int age;
	private String name;

	public int getAge(a) {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName(a) {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString(a) {
		return "Person [age=" + age + ", name=" + name + "]"; }}Copy the code

Then customize the class to implement the Converter interface and rewrite the method:

public class CustomConverter implements Converter<Person> {

	@Override
	public Person convert(Object value, Person person) throws IllegalArgumentException {
		person = new Person();
		String[] str = Convert.toStrArray(value);
		person.setAge(Convert.toInt(str[0]));
		person.setName(str[1]);
		returnperson; }}Copy the code

This method encapsulates the passed data as a Person object and returns it, performing type conversion.

Then register the custom converter:

ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
converterRegistry.putCustom(Person.class, CustomConverter.class);
Copy the code

Now we can use our converter, which is the code we just wrote:

String[] str = { "20"."Zhang" };
Person person = converterRegistry.convert(Person.class, str);
System.out.println(person);
Copy the code

The style of data that needs to be converted is entirely up to your custom converter, which is flexible and can be customized to your own needs.

Date and time processing

Java provides Date and Calendar classes for date-time processing, but with more options, DateUtil becomes confusing and complicated.

1. Mutual conversion of Date, Long and Calendar

DateUtil allows you to convert between Date, long, and Calendar as follows:

// Calendar changes to Date
Date date = DateUtil.date(Calendar.getInstance());
// Long becomes Date
Date date2 = DateUtil.date(System.currentTimeMillis());
// Date converts to Calendar
Calendar calendar = DateUtil.calendar(date);
// Long converts to Calendar
Calendar calendar2 = DateUtil.calendar(System.currentTimeMillis());
Copy the code

2. Convert the Date string to Date

String s = "2019-12-07";
DateTime dateTime = DateUtil.parse(s);
System.out.println(dateTime);
Copy the code

Running results:

2019-12-07 00:00:00
Copy the code

This method converts a Date string to Date. It automatically recognizes strings of the following formats:

  1. yyyy-MM-dd HH:mm:ss
  2. yyyy-MM-dd
  3. HH:mm:ss
  4. yyyy-MM-dd HH:mm
  5. yyyy-MM-dd HH:mm:ss.SSS

3. Format dates

Formatting dates is simple, just like the Java API.

String s = "2019-12-07";
DateTime date = DateUtil.parse(s);

String dateStr = DateUtil.format(date, "yyyy/MM/dd");
System.out.println(dateStr);
String dateStr2 = DateUtil.formatDate(date);
System.out.println(dateStr2);
String dateStr3 = DateUtil.formatDateTime(date);
System.out.println(dateStr3);
String dateStr4 = DateUtil.formatTime(date);
System.out.println(dateStr4);
Copy the code

The format() method converts a date string to a specified format, but DateUtil provides several other methods to convert the date string to a specified format.

2019/12/07
2019-12-07
2019-12-07 00:00:00
00:00:00
Copy the code

4. Get the year, month and day

DateUtil also provides a very easy way to get year, month, and day:

// Get the current date and time
DateTime date = DateUtil.date();
System.out.println(date);
/ / for years
int year = DateUtil.year(date);
System.out.println(year);
// Get month starts at 0
int month = DateUtil.month(date);	
System.out.println(month);
Copy the code

Running results:

2019-12-07 21:45:42
2019
11
Copy the code

5. Date and time offset

DateUtil can also be easily implemented for date-time offsets as follows:

String s = "The 2019-12-06 21:46:00";
DateTime date = DateUtil.parse(s);

// Set the date back one day
DateTime dateTime = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
System.out.println(dateTime);

// The date is moved back two days
DateTime dateTime2 = DateUtil.offsetDay(dateTime, 2);
System.out.println(dateTime2);

// The date is set back one hour
DateTime dateTime3 = DateUtil.offsetHour(date, 1);
System.out.println(dateTime3);
Copy the code

Running results:

2019-12-07 21:46:00
2019-12- 0921:46:00
2019-12-06 22:46:00
Copy the code

The offset() method is used to offset the date and time, and the second parameter is passed in the offset unit, but DateUtil also provides some common offset methods, such as offset days and offset hours.

DateUtil also provides some common methods for dates and times that are very close to the present, such as yesterday, tomorrow, last week, next week, last month, next month, and so on:

DateTime yesrerday = DateUtil.yesterday();
System.out.println(yesrerday);
		
DateTime tomorrow = DateUtil.tomorrow();
System.out.println(tomorrow);
		
DateTime lastMonth = DateUtil.lastMonth();
System.out.println(lastMonth);
		
DateTime nextMonth = DateUtil.nextMonth();
System.out.println(nextMonth);
		
DateTime lastWeek = DateUtil.lastWeek();
System.out.println(lastWeek);
		
DateTime nextWeek = DateUtil.nextWeek();
System.out.println(nextWeek);
Copy the code

Running results:

2019-12-06 22:02:29
2019-12- 0822:02:29
2019-11-07 22:02:29
2020-01-07 22:02:29
2019-11-30 22:02:29
2019-12-14 22:02:29
Copy the code

6. Calculate the time difference between dates

String s1 = "The 2019-12-06 22:15:00";
DateTime date1 = DateUtil.parse(s1);
String s2 = "The 2019-12-08 22:15:00";
DateTime date2 = DateUtil.parse(s2);
// Calculate the difference in days
long day = DateUtil.between(date1, date2, DateUnit.DAY);
System.out.println(day);
// Calculate the difference in hours
long hour = DateUtil.between(date1, date2, DateUnit.HOUR);
System.out.println(hour);
Copy the code

Running results:

2
48
Copy the code

The difference between two dates and times can be easily obtained using the between() method, whose third argument is the unit of the difference to be calculated.

7. Timer

The DateUtil class also encapsulates Timer functionality. As those of you who have used traditional Timer timers know, Timer timers are a bit more complex, while DateUtil encapsulates just right.

TimeInterval timer = DateUtil.timer();
// Delay 2 seconds
Thread.sleep(2000);
// Time spent in milliseconds
long interval = timer.interval();
System.out.println(interval);
// Time spent, in minutes
long intervalMinute = timer.intervalMinute();
System.out.println(intervalMinute);
Copy the code

Running results:

2000
0
Copy the code

There are many other methods, I don’t have enough space to mention them all.

8, other

DateUtil also offers solutions for more common scenarios, such as calculating a person’s age and determining whether a given year is a leap year.

int age = DateUtil.ageOfNow("1999-08-08");
System.out.println(age);
boolean leapYear = DateUtil.isLeapYear(2019);
System.out.println(leapYear);
Copy the code

Running results:

20
false
Copy the code

IO operations

IO operation is one of the most important operations in Java. For this reason, Java provides InputStream, OutputStream, Reader, Writer and other interfaces. However, there are many implementation classes. HuTool encapsulates a series of tool classes for us.

FileUtil(File manipulation utility class)

The FileUtil utility class is provided by HuTool to solve most of the file manipulation problems.

For those of you with Linux roots, the authors of the open source project tried to keep the method names consistent with Linux, such as creating files with touch() instead of createFile().

File[] files = FileUtil.ls("E:");
for (File file : files) {
	System.out.println(file);
}
Copy the code

Running results:

E:\$RECYCLE.BIN E:\androidSdk E:\androidstudio E:\b2631f36a0808f7d3cab19543d645e63 E:\flutter E:\Java E:\MailMasterData E:\QLDownload E:\QQPCmg E:\QQPCmgr E:\ qyCache E:\System Volume Information E:\test. TXT E:\Tool E:\ Thunderbolt DownloadCopy the code

The ls() method lists all directories and files in a given path.

FileUtil.touch("E:/test/hello.txt");
Copy the code

The touch() method is used to create a file. If the parent directory does not exist, the file is automatically created, such as hello.txt. If the test directory does not exist, the test folder is created first, and then the hello.txt file is created in the test directory.

The other methods are also used as shown above and will not be demonstrated in one example:

  • mkdirTo create a directory, each level of directory is created recursively
  • delDeleting a file or directory (recursively, without determining whether it is empty) is the Linux equivalent of the delete command
  • copyCopy files or directories

Note: With the del() method, it deletes the directory without determining whether it is empty, so use it with caution.

IOUtil(IO tool Class)

The second is IOUtil, a utility class that encapsulates input and output streams.

1. File replication

For file copying, IOUtil makes it easy.

BufferedInputStream inputStream = FileUtil.getInputStream("C:/Users/Administrator/Desktop/eclipseworkspace/HuToolDemo/src/com/wwj/test/TestDemo.java");
BufferedOutputStream outputStream = FileUtil.getOutputStream("E:/test.txt");
long copySize = IoUtil.copy(inputStream, outputStream, IoUtil.DEFAULT_BUFFER_SIZE);
Copy the code

Here we copy the current Java file and save it to test.txt on drive E.

2. Read flow Write flow

Read stream Write stream is also a frequently used OPERATION in I/O operations. It is not much different from the traditional method, but it is unified for callers.

BufferedInputStream inputStream = FileUtil.getInputStream("C:\\Users\\Administrator\\Desktop\\eclipseworkspace\\HuToolDemo\\src\\com\\wwj\\test\\TestDemo.Java");
BufferedOutputStream outputStream = FileUtil.getOutputStream("E:\\test.txt");
int len = -1;
byte[] buffer = new byte[1024];
while((len = inputStream.read(buffer)) ! = -1) {
	outputStream.write(buffer, 0, len);
}
IoUtil.close(inputStream);
IoUtil.close(outputStream);
Copy the code

The following lists the methods related to read/write stream operations:

  • readBytesReturn byte arrays (read images, etc.)
  • readHexRead hexadecimal strings
  • readObjReading a serialized object (deserialization)
  • readLinesAccording to the line read

IoUtil provides two override methods for write() for write stream operations, but it is also possible to use the write() method for output stream directly, which in fact IoUtil’s write() method does.

Let’s take a look at how IoUtil reads and writes images. For reading and writing images, it provides the readBytes() method, which isn’t too easy to use:

BufferedInputStream inputStream = FileUtil.getInputStream("C:\ Users\ Administrator\ Desktop\ eclipseWorkspace \HuToolDemo\ default chart.png");
BufferedOutputStream outputStream = FileUtil.getOutputStream("E:\\test.png");
byte[] bytes = IoUtil.readBytes(inputStream);
outputStream.write(bytes);
IoUtil.close(inputStream);
IoUtil.close(outputStream);
Copy the code

This can complete the picture read and write.

IoUtil also provides other methods to simplify programming, such as the toStream() method to convert some objects into stream objects; The writeObjects() method is used to serialize a serializable object and write it to the stream.

3. Release stream resources

A good practice in IO operations is to close each stream as it is used up, and closing operations face two problems:

  • The closed object is empty
  • Object closure failure

The close() method provided by IoUtil solves these problems nicely, simply passing what is to be closed into the close() method.

FileTypeUtil(File type determination utility class)

FileTypeUtil is a utility class that determines the file type not by the file extension, but by reading the first few bits of the file.

File file = FileUtil.file("C:\ Users\ Administrator\ Desktop\ eclipseWorkspace \HuToolDemo\ default chart.png");
String type = FileTypeUtil.getType(file);
Console.log(type);
Copy the code

Running results:

png
Copy the code

FileReader(File reading)

Although FileUtil already provides an API for reading and writing files, HuTool provides a FileReader class for reading files in accordance with the separation of responsibilities.

The FileReader class is also available in the JDK, but is not very useful, and HuTool is an update to it.

FileReader fileReader = new FileReader("test.properties");
String result = fileReader.readString();
System.out.println(result);
Copy the code

Running results:

username=root
password=123456
Copy the code

The class also provides some common methods to help read files:

  • readBytes
  • readString
  • readLines

File writing (FileWriter)

When a file is read, a file must be written, using the same method as FileReader, I won’t do the code demonstration here.

Write mode is divided into append and overwrite two modes, append can be used, overwrite can use write() method; You can also use the write() method and pass in the write mode as the second argument.

Access to resources

In Java development, resource access is a common operation. For example, when operating a database or integrating a framework, configuration files need to be frequently accessed. Configuration files are usually placed in the classpath for easy access:

InputStream in = TestDemo.class.getResource("test.properties").openStream();
Copy the code

HuTool encapsulates the frequent and cumbersome operations of resource access.

ClassPathResource resource = new ClassPathResource("test.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
Console.log(properties);
Copy the code

Running results:

{password=123456, username=root}
Copy the code

Of course, there is much more to encapsulating resource access, which will be explained later.

The last

This is just the tip of the iceberg for the HuTool project, and I’ll cover some of the packaged tool classes under this project in the next related article.