This is the 31st day of my participation in the August Text Challenge.More challenges in August
The previous article covered some of the components provided by the HuTool project, but there is much more to HuTool than that. Next, I’ll show you some of the convenience tools that HuTool provides.
If you have not read the previous article, it does not matter, it does not affect your understanding of the following content, but for the benefit of those who have directly read the second article, it is necessary to introduce HuTool.
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
For non-Maven projects, you can download the JAR package from Baidu and import it.
StrUtil
This is a utility class that handles strings.
There’s nothing more to say about strings, but let’s take a look at the methods it provides.
1, hasBlank, hasEmpty
Both methods are used to determine if a string is empty, as shown in the following code:
@Test
// Determine if the string is empty
public void hasBlankOrhasEmptyTest(a){
String str1 = "";
String str2 = "";
System.out.println(StrUtil.hasBlank(str1));
System.out.println(StrUtil.hasBlank(str2));
System.out.println(StrUtil.hasEmpty(str1));
System.out.println(StrUtil.hasEmpty(str2));
}
Copy the code
Running results:
true
true
false
true
Copy the code
Note that while both methods are used to determine whether a given string is empty, the hasEmpty method can only determine null and empty strings (“”), and the hasBlank method treats invisible characters as empty. For example, in the above program, for str1, whose value is an invisible character (space), the hasEmpty method does not empty the string, whereas the hasBlank method treats the string as empty. But for STR2, there is no ambiguity between the two methods and it is uniformly considered as null.
RemovePrefix, removeSuffix
These methods are used to remove the specified prefix and suffix from a string, respectively.
Look at the code:
@Test
// Removes the specified prefix and suffix from the string
public void removePrefixOrremoveSuffixTest(a){
String str1 = "test.jpg";
// remove the suffix
System.out.println(StrUtil.removeSuffix(str1,".jpg"));
// Remove the specified prefix
System.out.println(StrUtil.removePrefix(str1,"test"));
}
Copy the code
Running results:
test
.jpg
Copy the code
3, sub
This method is an improvement on the subString method provided by the JDK. Remember what the JDK subString method does?
It is used to intercept a string and return the corresponding subString by the given index. Since the traditional subString method has too many problems, what is the problem? Look at the code:
@Test
public void subTest(a){
String str = "hello world";
System.out.println(str.substring(0.12));
}
Copy the code
In this program, the length of the string STR is 11, but the truncation of the string length is 12, obviously the index crossed the boundary, but sometimes we can make this error, but it is not a good way to run the error. To do this, StrUtil provides a sub method, which takes into account all sorts of considerations and handles them accordingly. It also supports a negative index, -1 for the last character, which is Python style.
The code is as follows:
@Test
// Intercepts a string
//index starts at 0 and ends with -1
// If from and to are the same, return ""
// If from or to is negative, the value of the absolute value is greater than the length of the string, the value of from is 0, and the value of to is length
// Swap from and to if from is greater than to in the corrected index
public void subTest(a){
String str = "hello world";
System.out.println(StrUtil.sub(str,0.12));
}
Copy the code
Even if your index position is extremely wrong, the sub method can easily handle it. The result of this program is:
hello world
Copy the code
4, the format
This method is used to format text. You can use a string template instead of string concatenation.
@Test
// Format the text
public void formatTest(a){
String str = "{} The blackbird flies {}";
String formatStr = StrUtil.format(str, "Thousand"."Never");
System.out.println(formatStr);
}
Copy the code
Running results:
Not a bird over hundreds of peaksCopy the code
This method uses {} as placeholders and then replaces the placeholders in the order of the arguments, so be careful where the arguments are placed. If you put the “absolute” word first, the result will be different.
@Test
// Format the text
public void formatTest(a){
String str = "{} The blackbird flies {}";
String formatStr = StrUtil.format(str, "Never"."Thousand");
System.out.println(formatStr);
}
Copy the code
Running results:
Mountain birds fly thousandsCopy the code
URLUtil
This utility class is dedicated to working with urls.
1, the url
This method converts a string to a URL object as follows:
@Test
// Convert a string to a URL object
public void urlTest(a) {
URL url = URLUtil.url("http://localhost:8080/name=zhangsan&age=20");
// Get the domain name part of the URL, keeping only the protocol in the URL
URI uri = URLUtil.getHost(url);
System.out.println(uri);
}
Copy the code
Running results:
http://localhost
Copy the code
2, getURL
This method is used to get a URL, usually when absolute paths are used, and the code is as follows:
@Test
// Get the URL, often used when absolute paths are used
public void getURLTest(a) {
URL url = URLUtil.getURL(FileUtil.file("URLUtilTest.java"));
System.out.println(url.toString());
}
Copy the code
Running results:
file:/C:/Users/Administrator/Desktop/ideaworkspace/HuTool/out/production/HuTool/URLUtilTest.java
Copy the code
This method gets the absolute path of the file by name, which is handy in scenarios where absolute paths are used.
3, normalize
This method is used to standardize URL links as follows:
@Test
// Standardize URL links
public void normalizeTest(a) {
String url = "www.baidu.com\\example\\test/a";
String newUrl = URLUtil.normalize(url);
System.out.println(newUrl);
}
Copy the code
Running results:
http://www.baidu.com/example/test/a
Copy the code
This method automatically completes and formats links without the http:// header.
4, getPath
This method is used to get the path part of the string in the URL link, for example:
@Test
// Get the path section
public void getPathTest(a) {
String url = "http://localhost/search? name=abc&age=20";
String pathStr = URLUtil.getPath(url);
System.out.println(pathStr);
}
Copy the code
Running results:
/search
Copy the code
ObjectUtil
In our everyday use, there are methods that are generic for objects and do not discriminate between objects. For these methods, Hutool encapsulates ObjectUtil.
1, equal
This method is used to compare whether two objects are equal under two conditions:
- obj1 == null && obj2 == null
- obj1.equal(obj2)
If one of these conditions is met, the two objects are equal, as follows:
@Test
// Compare whether two objects are equal.
// There are two identical conditions, one of which can be satisfied:
//obj1 == null && obj2 == null obj1.equals(obj2)
public void equalTest(a) {
Object obj = null;
Object obj2 = null;
boolean equal = ObjectUtil.equal(obj, obj2);
System.out.println(equal);
}
Copy the code
Running results:
true
Copy the code
2, length,
This method is used to calculate the length of the object passed in, or if it is a string; If a collection is passed in, the collection size is computed; The length method automatically calls the length calculation method of the corresponding type.
@Test
The collection class calls its size function, the array calls its length property, and other traversable objects count the length
// The following types are supported: CharSequence Map Iterator Enumeration Array
public void lengthTest(a) {
String str = "hello world";
List<Integer> list = Arrays.asList(1.2.3.4.5.6);
System.out.println(ObjectUtil.length(str));
System.out.println(ObjectUtil.length(list));
}
Copy the code
Running results:
11
6
Copy the code
3, the contains
This method is used to determine whether the specified element exists in a given object, as follows:
@Test
// Whether the object contains elements
The supported object types are String Collection Map Iterator Enumeration Array
public void containsTest(a) {
List<Integer> list = Arrays.asList(1.2.3.4.5.6);
boolean flag = ObjectUtil.contains(list, 1);
System.out.println(flag);
}
Copy the code
Running results:
true
Copy the code
4, isBasicType
This method is used to determine whether a given object is a primitive type, both wrapped and unwrapped, with the following code:
@Test
// Whether it is a basic type, including wrapped type and unwrapped type
public void isBasicTypeTest(a){
String str = "hello";
int num = 100;
boolean flag = ObjectUtil.isBasicType(str);
boolean flag2 = ObjectUtil.isBasicType(num);
System.out.println(flag);
System.out.println(flag2);
}
Copy the code
Running results:
false
true
Copy the code
ReflectUtil
Reflection mechanism is the core of Java, Java framework implementation uses a lot of reflection, HuTool for Java reflection to do some packaging.
1, getMethods
This method is used to get all the methods in a class, including those in its parent class.
@Test
// Get a list of all methods in a class, including those in its parent class
public void getMethodsTest(a) {
Method[] methods = ReflectUtil.getMethods(Object.class);
for(Method method : methods) { System.out.println(method.getName()); }}Copy the code
Running results:
finalize
wait
wait
wait
equals
toString
hashCode
getClass
clone
notify
notifyAll
registerNatives
Copy the code
2, getMethod
This method is used to get the specified method of a class as follows:
@Test
// Gets the specified method of a class
public void getMethodsTest(a) {
Method method = ReflectUtil.getMethod(Object.class, "getClass");
System.out.println(method);
}
Copy the code
Running results:
public final native java.lang.Class java.lang.Object.getClass()
Copy the code
* * 3, newInstance * *
This method instantiates an object using the Class type of the Class, as follows:
@Test
// instantiate the object
public void newInstanceTest(a) {
Object obj = ReflectUtil.newInstance(Object.class);
boolean flag = ObjectUtil.isNull(obj);
System.out.println(flag);
}
Copy the code
Running results:
false
Copy the code
4, invoke
This method is used to execute the methods in the object, with the following code:
@Test
// Execute method
public void invokeTest(a) {
ArrayList list = ReflectUtil.newInstance(ArrayList.class);
ReflectUtil.invoke(list,"add".1);
System.out.println(list);
}
Copy the code
Running results:
[1]
Copy the code
The second parameter is the name of the method to execute, and the third parameter is the method parameter to execute.
ClipboardUtil
This is a clipboard utility class to simplify operations on the clipboard, which may be used in some scenarios.
1, getStr
This method is used to retrieve the contents of the clipboard. For example, if you select a section of the content and copy it with the mouse, this method can obtain the copied content, the code is as follows:
@Test
// Get text content from the clipboard
public void getStrTest(a) {
String str = ClipboardUtil.getStr();
System.out.println(str);
}
Copy the code
Running results:
String str = ClipboardUtil.getStr();
Copy the code
2, setStr
This method sets the contents of the clipboard, that is, you copy the contents of the clipboard by setting the specified string to the clipboard as follows:
@Test
// Sets the clipboard text content
public void setStrTest(a) {
String str = ClipboardUtil.getStr();
System.out.println(str);
ClipboardUtil.setStr("hello world");
String str2 = ClipboardUtil.getStr();
System.out.println(str2);
}
Copy the code
Running results:
String str = ClipboardUtil.getStr();
hello world
Copy the code
There are methods to get pictures, set pictures and so on, we can experience.
ClassUtil
This class mainly encapsulates some reflection methods, making it easier to call.
1, getShortClassName
This method is used to get the short format of the class name as follows:
@Test
// Get the short format of the class name
public void getShortClassNameTest(a){
String shortClassName = ClassUtil.getShortClassName("com.wwj.hutool.test.ObjectUtilTest");
System.out.println(shortClassName);
}
Copy the code
Running results:
c.w.h.t.ObjectUtilTest
Copy the code
2, getPackage
Gets the package name of the specified class as follows:
@Test
// Gets the package name of the specified class
public void getPackageTest(a){
String packageName = ClassUtil.getPackage(ObjectUtilTest.class);
System.out.println(packageName);
}
Copy the code
Running results:
com.wwj.hutool.test
Copy the code
3, scanPackage
This method is at the heart of the utility class. It is a method that scans resources under a package and is used in Spring for dependency injection as follows:
@Test
// Scan for resources under packets
public void scanPackageTest(a){ Set<Class<? >> classes = ClassUtil.scanPackage("com.wwj.hutool.test");
for (Class<?> aclass : classes) {
System.out.println(aclass.getName());
}
}
Copy the code
Running results:
com.wwj.hutool.test.URLUtilTest
com.wwj.hutool.test.StrUtilTest
com.wwj.hutool.test.ObjectUtilTest
Copy the code
This method takes a package name as an argument and scans all classes under the specified package. You can also filter out the specified class by passing in a ClassFilter object.
4, getJavaClassPaths
This method is used to get the ClassPath defined by Java’s system variables.
@Test
public void scanPackageTest(a){
String[] javaClassPaths = ClassUtil.getJavaClassPaths();
for(String javaClassPath : javaClassPaths) { System.out.println(javaClassPath); }}Copy the code
Running results:
F:\Tool\IntelliJ IDEA 2018.3\lib\idea_rt.jar
F:\Tool\IntelliJ IDEA 2018.3\plugins\junit\lib\junit-rt.jar
F:\Tool\IntelliJ IDEA 2018.3\plugins\junit\lib\junit5-rt.jar
E:\Java\jdk18.. 0 _181\jre\lib\charsets.jar
E:\Java\jdk18.. 0 _181\jre\lib\deploy.jar
......
Copy the code
RuntimeUtil
This utility class is used to execute command line commands, CMD on Windows and shell on Linux.
Because it’s easy, just post the code:
@Test
public void RunTimeUtilTest(a){
String str = RuntimeUtil.execForStr("ipconfig");
System.out.println(str);
}
Copy the code
Running results:
Windows IP Configuration Ethernet Adapter Ethernet: media status............ : Media disconnected Connection specific DNS suffix....... : Wireless LAN adapter Local connection *1: media status............ : Media disconnected Connection specific DNS suffix....... : wireless LAN adapter Local connection *2: Media status............ : Media is disconnected Connect specific DNS suffix....... : wireless LAN adapter WLAN: Connect specific DNS suffix....... : www.tendawifi.com Local link IPv6 address........ : fe80::830:2d92:1427:a434%17IPv4 address............ :192.168. 0103.Subnet mask............ :255.255255.. 0Default gateway............. :192.168. 01.
Copy the code
NumberUtil
This is a utility class for mathematical operations. In traditional Java development, you often encounter computations between decimals that can easily lose precision. For accuracy, you often use BigDecimal classes, but converting between them is complicated. For this purpose, HuTool provides the NumberUtil class, which makes mathematical calculations very easy to use.
1. Addition, subtraction, multiplication and division
@Test
public void calcTest(a){
double d = 3.5;
float f = 0.5 f;
System.out.println(NumberUtil.add(d,f));/ / add
System.out.println(NumberUtil.sub(d,f));/ /
System.out.println(NumberUtil.mul(d,f));/ / by
System.out.println(NumberUtil.div(d,f));/ / in addition to
}
Copy the code
Running results:
4.0
3.0
1.75
7.0
Copy the code
2. Keep decimals
@Test
public void calcTest(a){
double d = 1234.56789;
System.out.println(NumberUtil.round(d,2));
System.out.println(NumberUtil.roundStr(d,3));
}
Copy the code
Running results:
1234.57
1234.568
Copy the code
The round and roundStr methods can be used to preserve decimals. The default mode is round, but you can also pass in the corresponding mode change program.
3. Numerical judgment
NumberUtil provides a series of methods for determining common types of numbers, so it’s easy to skip the code and just look at the method name and what it does.
NumberUtil.isNumber
Is it a number?NumberUtil.isInteger
Is it an integer?NumberUtil.isDouble
Whether it is a floating point numberNumberUtil.isPrimes
Whether it’s prime
4, other
Of course, there are some more common math operations that NumberUtil encapsulates.
NumberUtil.factorial
factorialNumberUtil.sqrt
The square rootNumberUtil.divisor
Greatest common divisorNumberUtil.multiple
Least common multipleNumberUtil.getBinaryStr
Gets the binary string corresponding to the numberNumberUtil.binaryToInt
Binary to intNumberUtil.binaryToLong
Binary to longNumberUtil.compare
Compares the size of two valuesNumberUtil.toStr
Number to string, automatically and remove redundant zeros after the last decimal point
IdUtil
This utility class is primarily used to generate unique ids.
1. Generate the UUID
@Test
public void IdUtilTest(a){
String uuid = IdUtil.randomUUID();
String simpleUUID = IdUtil.simpleUUID();
System.out.println(uuid);
System.out.println(simpleUUID);
}
Copy the code
Running results:
b1e4e753-39b9-4026-8a08-ce9837e15f62
23f1603604694d029bb35c1c03d7aeb1
Copy the code
The ramdimUUID method produces a UUID with a ‘-‘, while the simpleUUID method produces a UUID without a ‘-‘.
2, the ObjectId
ObjectId is a unique ID generation policy for the MongoDB database. It is a variant of UUID version1.
Hutool against the encapsulates the cn. Hutool. Core. Lang. ObjectId, quickly create method is:
// Generate similar: 5b9e306a4df4f8C54a39fb0c
String id = ObjectId.next();
// Method 2: Start with hutool-4.1.14
String id2 = IdUtil.objectId();
Copy the code
3, Snowflake
In distributed systems, there are some scenarios where globally unique ids are required, and sometimes we want to use a simpler ID that can be generated in chronological order. Twitter’s Snowflake algorithm is one such generator.
The usage method is as follows:
// Parameter 1 is the terminal ID
// Parameter 2 is the ID of the data center
Snowflake snowflake = IdUtil.createSnowflake(1.1);
long id = snowflake.nextId();
Copy the code
ZipUtil
In Java, packing and compressing files and folders is a tedious task, and we often introduce Zip4j to do this. But in many cases, the ZIP package in the JDK will do most of the job. ZipUtil is a tool package for java.util.zip, so that the compression and decompression operations can be done in one way, and automatically handle file and directory problems, no longer need to judge the user, compressed files will automatically create files, automatically create a parent directory, greatly simplifying the compression and decompression complexity.
1, Zip,
@Test
public void zipUtilTest(a){
ZipUtil.zip("C:/Users/Administrator/Desktop/test.txt");
}
Copy the code
Observe the desktop:Compression succeeded.
Of course, you can also specify the location of the compressed package by passing the path to the zip method as the second parameter.
Multiple file or directory compression. You can select multiple files or directories into a ZIP package:
@Test
public void zipUtilTest(a) {
ZipUtil.zip(FileUtil.file("d:/bbb/ccc.zip"), false,
FileUtil.file("d:/test1/file1.txt"),
FileUtil.file("d:/test1/file2.txt"),
FileUtil.file("d:/test2/file1.txt"),
FileUtil.file("d:/test2/file2.txt")); }Copy the code
The decompression method is unzip.
2, GZip
Gzip is a widely used compression method for web page delivery, and Hutool also provides its own tool method to simplify the process.
Ziputil. gzip ziputil. gzip ziputil. unGzip ziputil. unGzip ziputil. unzip gzip files
3, Zlib
ZipUtil zlib compression, compressible string, can also be compressed file ZipUtil. UnZlib decompression zlib file
IdCardUtil
In daily development, we mainly verify the ID card in regular mode (digit, number range, etc.), but The Chinese ID card, especially the 18-digit ID card, has strict rules for each bit, and the last bit is the check bit. And in our practical application, the verification of id card should be strict so far. IdcardUtil was born.
IdcardUtil now supports 15-digit and 18-digit ids for mainland China and 10-digit IDS for Hong Kong, Macao and Taiwan.
The main methods in the tool include:
isValidCard
Verify your ID card is legitimateconvert15To18
Id card 15 digits to 18 digitsgetBirthByIdCard
For birthdaygetAgeByIdCard
For agegetYearByIdCard
Get birthday yeargetMonthByIdCard
Get birthday monthgetDayByIdCard
Get birthday daygetGenderByIdCard
For gendergetProvinceByIdCard
Obtain province
use
String ID_18 = "321083197812162119";
String ID_15 = "150102880730303";
// Whether it is valid
boolean valid = IdcardUtil.isValidCard(ID_18);
boolean valid15 = IdcardUtil.isValidCard(ID_15);
/ / conversion
String convert15To18 = IdcardUtil.convert15To18(ID_15);
Assert.assertEquals(convert15To18, "150102198807303035");
/ / age
DateTime date = DateUtil.parse("2017-04-10");
int age = IdcardUtil.getAgeByIdCard(ID_18, date);
Assert.assertEquals(age, 38);
int age2 = IdcardUtil.getAgeByIdCard(ID_15, date);
Assert.assertEquals(age2, 28);
/ / birthday
String birth = IdcardUtil.getBirthByIdCard(ID_18);
Assert.assertEquals(birth, "19781216");
String birth2 = IdcardUtil.getBirthByIdCard(ID_15);
Assert.assertEquals(birth2, "19880730");
/ / provinces
String province = IdcardUtil.getProvinceByIdCard(ID_18);
Assert.assertEquals(province, "Jiangsu");
String province2 = IdcardUtil.getProvinceByIdCard(ID_15);
Assert.assertEquals(province2, Inner Mongolia);
Copy the code
The last
This article has just taken a look at some of the tool classes in HuTool. In fact, HuTool is a very nice project that implements a lot of Java operations, making it easy for us to handle some of the more complex things.
For more information about HuTool, you can learn about it yourself.