Hutool - make Java programming more efficient

This article will introduce some handy tools HuTool to us.

First, add the following dependencies pom.xml in the project:

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
复制代码

Non-Maven project, then download it on their own Baidu jar package, you can import.

二, StrUtil

Look at this name should also understand that this is the kind of tool string processing.

About strings, we have nothing to introduce a direct look at what methods it provides to us.

1、hasBlank、hasEmpty

Both methods are used to determine whether the string is empty, see the following code:

@Test
//判断字符串是否为空
public void hasBlankOrhasEmptyTest{
  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));
}
复制代码

operation result:

true
true
false
true
复制代码

It should be noted that, although the role of these two methods is to determine whether a given string is empty, but hasEmpty method can only be judged and an empty string ( ""), and hasBlank method will also be invisible characters considered null. Such as the above program, for str1, it is invisible character (space), hasEmpty method of the string is not empty, the method considers hasBlank the string is empty; but there is no ambiguity for str2, two methods, unified finds it empty.

2、removePrefix、removeSuffix

These two methods are used to specify the prefix and suffix removal string.

Look at the code:

 @Test
//去除字符串的指定前缀和后缀
public void removePrefixOrremoveSuffixTest{
  String str1 = "test.jpg";
  //去除指定后缀
  System.out.println(StrUtil.removeSuffix(str1,".jpg"));
  //去除指定前缀
  System.out.println(StrUtil.removePrefix(str1,"test"));
}
复制代码

operation result:

test
.jpg
复制代码

3、sub

This method provides an improved self subString method JDK, remember the JDK subString method is doing it?

It is used to intercept the string by returning the substring corresponding to the given index, due to the traditional method of subString too many questions, you ask me what is the problem? Look at the code:

 @Test
public void subTest{
  String str = "hello world";
  System.out.println(str.substring(0,12));
}
复制代码

During this procedure, the length of the string str is 11, but in time to intercept the string length has intercepted 12, apparently index out of bounds, but sometimes it's easy to make this mistake, the error can not be directly run a good way. To this end, StrUtil provides us with sub method, which takes into account a variety of circumstances need to be considered and made the appropriate treatment, at the same time, it also supports the index is negative, -1 is the last character, the Python style, author it should be a Python fan.

code show as below:

 @Test
//截取字符串
//index从0开始计算,最后一个字符为-1
//如果from和to位置一样,返回 ""
//如果from或to为负数,则按照length从后向前数位置,如果绝对值大于字符串长度,则from归到0,to归到length
//如果经过修正的index中from大于to,则互换from和to
public void subTest{
  String str = "hello world";
  System.out.println(StrUtil.sub(str,0,12));
}
复制代码

At this time, even if your index position is extremely outrageous, sub method can easily deal with, the results of the program are:

hello world
复制代码

4、format

The method for formatting text string may be used instead of template string concatenation, look at the code:

 @Test
//格式化文本
public void formatTest{
  String str = "{}山鸟飞{}";
  String formatStr = StrUtil.format(str, "千", "绝");
  System.out.println(formatStr);
}
复制代码

operation result:

千山鸟飞绝
复制代码

The method} as a placeholder, and according to the parameters by replacing {order placeholder, the position of the parameter must be noted that if the "no" in front of the word, the result is not the same.

 @Test
//格式化文本
public void formatTest{
  String str = "{}山鸟飞{}";
  String formatStr = StrUtil.format(str, "绝", "千");
  System.out.println(formatStr);
}
复制代码

operation result:

绝山鸟飞千
复制代码

Three, URLUtil

Tools designed for use with the url.

1、url

By this method a URL string can be converted to an object, as follows:

 @Test
//将字符串转换为URL对象
public void urlTest {
  URL url = URLUtil.url("http://localhost:8080/name=zhangsan&age=20");
  //获取URL中域名部分,只保留URL中的协议
  URI uri = URLUtil.getHost(url);
  System.out.println(uri);
}
复制代码

operation result:

http://localhost
复制代码

2、getURL

The method for obtaining the URL, commonly used in the case when using an absolute path, as follows:

 @Test
//获得URL,常用于使用绝对路径时的情况
public void getURLTest {
  URL url = URLUtil.getURL(FileUtil.file("URLUtilTest.java"));
  System.out.println(url.toString);
}
复制代码

operation result:

file:/C:/Users/Administrator/Desktop/ideaworkspace/HuTool/out/production/HuTool/URLUtilTest.java
复制代码

This method can get the file name to an absolute path to the file, which is very convenient in the scene using the absolute path.

3、normalize

The method used to normalize a URL link, as follows:

 @Test
//标准化化URL链接
public void normalizeTest {
  String url = "www.baidu.com\\example\\test/a";
  String newUrl = URLUtil.normalize(url);
  System.out.println(newUrl);
}
复制代码

operation result:

http://www.baidu.com/example/test/a
复制代码

This method would be without HTTP : // links head of auto-completion, and a unified format.

4, getPath

The method for obtaining the URL link path portion of the string, such as:

 @Test
//获得path部分
public void getPathTest {
  String url = "http://localhost/search?name=abc&age=20";
  String pathStr = URLUtil.getPath(url);
  System.out.println(pathStr);
}
复制代码

operation result:

/search
复制代码

Four, ObjectUtil

In our daily use, some methods for the Object general, these methods do not distinguish between objects which, for these methods, Hutool package is ObjectUtil.

1、equal

The method used to compare two objects are equal, equal to two conditions:

  1. obj1 == && obj2 ==
  2. obj1.equal(obj2)

Both conditions are satisfied where a denotes equal on these two objects, as follows:

 @Test
//比较两个对象是否相等。
//相同的条件有两个,满足其一即可:
//obj1 == && obj2 == obj1.equals(obj2)
public void equalTest {
  Object obj = ;
  Object obj2 = ;
  boolean equal = ObjectUtil.equal(obj, obj2);
  System.out.println(equal);
}
复制代码

operation result:

true
复制代码

2、length

The method for calculating the length of the incoming object, if the incoming string, the string length is calculated; If the incoming is set, the set size is calculated; longitudinal length calculation method will automatically call the corresponding type.

 @Test
//计算对象长度,如果是字符串调用其length函数,集合类调用其size函数,数组调用其length属性,其他可遍历对象遍历计算长度
//支持的类型包括:CharSequence Map Iterator Enumeration Array
public void lengthTest {
  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));
}
复制代码

operation result:

11
6
复制代码

3、contains

This method is used in a given object is determined whether there is a specified element, as follows:

 @Test
//对象中是否包含元素
//支持的对象类型包括:String Collection Map Iterator Enumeration Array
public void containsTest {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
boolean flag = ObjectUtil.contains(list, 1);
System.out.println(flag);
}
复制代码

operation result:

true
复制代码

4、isBasicType

The method for determining whether a given object is a primitive type, comprising a non-package type and package types, as follows:

 @Test
//是否为基本类型,包括包装类型和非包装类型
public void isBasicTypeTest{
  String str = "hello";
  int num = 100;
  boolean flag = ObjectUtil.isBasicType(str);
  boolean flag2 = ObjectUtil.isBasicType(num);
  System.out.println(flag);
  System.out.println(flag2);
}
复制代码

operation result:

false
true
复制代码

Five, ReflectUtil

Java's reflection mechanism is the core, the framework on the use of Java to a lot of reflection, HuTool made some package for the Java reflection.

1、getMethods

The method for obtaining a class of all the methods, including the methods of its parent class.

 @Test
//获得一个类中所有方法列表,包括其父类中的方法
public void getMethodsTest {
  Method methods = ReflectUtil.getMethods(Object.class);
  for (Method method : methods) {
  	System.out.println(method.getName);
  }
}
复制代码

operation result:

finalize
wait
wait
wait
equals
toString
hashCode
getClass
clone
notify
notifyAll
registerNatives
复制代码

2、getMethod

The method to specify a method for obtaining a class code is as follows:

 @Test
//获取某个类的指定方法
public void getMethodsTest {
  Method method = ReflectUtil.getMethod(Object.class, "getClass");
  System.out.println(method);
}
复制代码

operation result:

public final native java.lang.Class java.lang.Object.getClass
复制代码

3、newInstance

In the method of class Class object type instances, as follows:

 @Test
//实例化对象
public void newInstanceTest {
  Object obj = ReflectUtil.newInstance(Object.class);
  boolean flag = ObjectUtil.is(obj);
  System.out.println(flag);
}
复制代码

operation result:

false
复制代码

4、invoke

The method for performing the method object code is as follows:

 @Test
//执行方法
public void invokeTest {
  ArrayList list = ReflectUtil.newInstance(ArrayList.class);
  ReflectUtil.invoke(list,"add",1);
  System.out.println(list);
}
复制代码

operation result:

[1]
复制代码

Wherein the second parameter is the name of the method to be executed, the third parameter is a parameter to execute the method.

六、ClipboardUtil

This class is a clipboard tool, is used to simplify operation of the clipboard may be used to certain scenarios.

1、getStr

The method for obtaining the contents of the clipboard, for example, you use the mouse to select a piece of content copy, the method may copy the contents acquired, as follows:

 @Test
//从剪切板获取文本内容
public void getStrTest {
  String str = ClipboardUtil.getStr;
  System.out.println(str);
}
复制代码

operation result:

String str = ClipboardUtil.getStr;
复制代码

2、setStr

The method used to set the contents of the clipboard, namely: setting the specified string to the clipboard, the copy content corresponding to you, as follows:

 @Test
//设置剪切板文本内容
public void setStrTest {
  String str = ClipboardUtil.getStr;
  System.out.println(str);
  ClipboardUtil.setStr("hello world");
  String str2 = ClipboardUtil.getStr;
  System.out.println(str2);
}
复制代码

operation result:

String str = ClipboardUtil.getStr;
hello world
复制代码

As well as get the picture, pictures, etc. set method, you can own experience.

Seven, ClassUtil

Such methods are mainly a reflection of the package, so that the call is more convenient.

1、getShortClassName

The method used to obtain the short format class name, as follows:

 @Test
//获取类名的短格式
public void getShortClassNameTest{
  String shortClassName = ClassUtil.getShortClassName("com.wwj.hutool.test.ObjectUtilTest");
  System.out.println(shortClassName);
}
复制代码

operation result:

c.w.h.t.ObjectUtilTest
复制代码

2、getPackage

Get the specified class package name, as follows:

 @Test
//获取指定类的包名
public void getPackageTest{
  String packageName = ClassUtil.getPackage(ObjectUtilTest.class);
  System.out.println(packageName);
}
复制代码

operation result:

com.wwj.hutool.test
复制代码

3, scanPackage

This method is the core of the tool or the like, which is a method of scanning the packet resources for dependency injection Spring code is as follows:

 @Test
//扫描包下资源
public void scanPackageTest{
  Set<Class<?>> classes = ClassUtil.scanPackage("com.wwj.hutool.test");
  for (Class<?> aclass : classes) {
  	System.out.println(aclass.getName);
  }
}
复制代码

operation result:

com.wwj.hutool.test.URLUtilTest
com.wwj.hutool.test.StrUtilTest
com.wwj.hutool.test.ObjectUtilTest
复制代码

This method needs to pass a package name as a parameter, then it will scan all the classes in the specified package, you can also filter out incoming ClassFilter object to the specified class.

4、getJavaClassPaths

The method used to obtain ClassPath Java system variables defined.

 @Test
public void scanPackageTest{
  String javaClassPaths = ClassUtil.getJavaClassPaths;
  for (String javaClassPath : javaClassPaths) {
  	System.out.println(javaClassPath);
  }
}
复制代码

operation result:

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\jdk1.8.0_181\jre\lib\charsets.jar
E:\Java\jdk1.8.0_181\jre\lib\deploy.jar
......
复制代码

八、RuntimeUtil

The tools used to execute the command in Windows is cmd, it is a shell under Linux.

Because it is simple, here directly posted code:

@Test
public void RunTimeUtilTest{
  String str = RuntimeUtil.execForStr("ipconfig");
  System.out.println(str);
}
复制代码

operation result:

Windows IP 配置


以太网适配器 以太网:

媒体状态 . . . . . . . . . . . . : 媒体已断开连接
连接特定的 DNS 后缀 . . . . . . . :

无线局域网适配器 本地连接* 1:

媒体状态 . . . . . . . . . . . . : 媒体已断开连接
连接特定的 DNS 后缀 . . . . . . . :

无线局域网适配器 本地连接* 2:

媒体状态 . . . . . . . . . . . . : 媒体已断开连接
连接特定的 DNS 后缀 . . . . . . . :

无线局域网适配器 WLAN:

连接特定的 DNS 后缀 . . . . . . . : www.tendawifi.com
本地链接 IPv6 地址. . . . . . . . : fe80::830:2d92:1427:a434%17
IPv4 地址 . . . . . . . . . . . . : 192.168.0.103
子网掩码 . . . . . . . . . . . . : 255.255.255.0
默认网关. . . . . . . . . . . . . : 192.168.0.1
复制代码

Nine, NumberUtil

This is a tool for math class in traditional Java development, often encounter calculated between decimal and fractional easily lose precision, for accurate, often used to BigDecimal class, but the conversion between them really complex. To this end, HuTool provides NumberUtil class, the use of such mathematical calculations will be very easy.

1, Math

@Test
public void calcTest{
  double d = 3.5;
  float f = 0.5f;
  System.out.println(NumberUtil.add(d,f));//加
  System.out.println(NumberUtil.sub(d,f));//减
  System.out.println(NumberUtil.mul(d,f));//乘
  System.out.println(NumberUtil.div(d,f));//除
}
复制代码

operation result:

4.0
3.0
1.75
7.0
复制代码

2 decimals

 @Test
public void calcTest{
  double d = 1234.56789;
  System.out.println(NumberUtil.round(d,2));
  System.out.println(NumberUtil.roundStr(d,3));
}
复制代码

operation result:

1234.57
1234.568
复制代码

By round and roundStr methods can achieve decimals, rounding the default mode, of course, you can also pass the appropriate mode change program.

3, digital judgment

NumberUtil provides a series of methods for common types of digital judgment, because it is simple, do not paste the code a direct look at the method name and role can be.

  • NumberUtil.isNumberIs a number
  • NumberUtil.isIntegerWhether an integer
  • NumberUtil.isDoubleWhether the float
  • NumberUtil.isPrimesIt is prime

4, other

Of course, there are some of the more common mathematical operations, NumberUtil also a corresponding package.

  • NumberUtil.factorialfactorial
  • NumberUtil.sqrtSquare root
  • NumberUtil.divisorGreatest common divisor
  • NumberUtil.multipleThe least common multiple
  • NumberUtil.getBinaryStrObtaining a digital binary string corresponding
  • NumberUtil.binaryToIntBinary int
  • NumberUtil.binaryToLongBinary long
  • NumberUtil.compareComparing two values
  • NumberUtil.toStrNumeric string transfer, and automatically removing the excess tail decimal child 0

Ten, IdUtil

The principal tool used to generate a unique ID.

1, generated UUID

@Test
public void IdUtilTest{
  String uuid = IdUtil.randomUUID;
  String simpleUUID = IdUtil.simpleUUID;
  System.out.println(uuid);
  System.out.println(simpleUUID);
}
复制代码

operation result:

b1e4e753-39b9-4026-8a08-ce9837e15f62
23f1603604694d029bb35c1c03d7aeb1
复制代码

ramdimUUID method is generated with '-' the UUID, and the method of generating the simpleUUID without - the UUID of ''.

2、ObjectId

ObjectId is a unique ID generation strategy MongoDB database, is the UUID version1 variants.

Hutool for this encapsulates cn.hutool.core.lang.ObjectId, create a shortcut method:

//生成类似:5b9e306a4df4f8c54a39fb0c
String id = ObjectId.next;

//方法2:从Hutool-4.1.14开始提供
String id2 = IdUtil.objectId;
复制代码

3、Snowflake

Distributed systems, some need to use the globally unique ID scenes, sometimes we want to use a simple number of ID, ID and want to be able to generate in chronological order. Twitter's algorithm is this Snowflake generator.

** The disadvantage is: ** strongly dependent on the time machine, if the machine to roll back time, it may result in duplicate id.

Use as follows:

// 参数1为终端ID,参数2为数据中心ID// 参数1、2的取值范围为[0,32),整数intSnowflake snowflake = IdUtil.getSnowflake(1, 1);
long id = snowflake.nextId;
复制代码

Note: You can also use IdUtil.createSnowflake (1, 1) is generated Snowflake. If combined with the for loop, you need to pay attention to the wording, or will cause duplicate id. But still recommended to use IdUtil.createSnowflake (1, 1), convenient no repeat.

Eleven, ZipUtil

In Java, the package file folder, file, compression is a more complicated thing, we often introduced Zip4j for such operations. But many times, JDK in the zip package can meet most of our needs. ZipUtil is aimed java.util.zip package of tools to do the compression and decompression operations can be a way to get, and automatically deal with files and directories, users no longer need to judge, the compressed file will automatically create a file, automatically create parent catalog, greatly simplifying the complexity of extracting compressed.

1、Zip

 @Test
public void zipUtilTest{
	ZipUtil.zip("C:/Users/Administrator/Desktop/test.txt");
}
复制代码

Desktop observed:

Compression success.

After the course, you can specify the storage location of the compressed packet, the path parameter as the second method may be passed zip.

Compress multiple files or directories. You can select multiple files or directories labeled with the zip package:

@Test
public void zipUtilTest {
	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")
  );

}
复制代码

Compression and decompression operation, as no explanation is repeated, decompression method unzip.

2、GZip

Gzip compression is widely used in transmission of the page, Hutool method also provides tools which simplify the process.

ZipUtil.gzipCompression, compressible string, compressible files ZipUtil.unGzipdecompress Gzip file

3、Zlib

ZipUtil.zlibCompression, compressible string, compressible files ZipUtil.unZlibunzip the file zlib

Twelve, IdCardUtil

In the daily development, we verify the identity of the principal is a regular way (median, range of numbers, etc.), but the Chinese ID card, ID card, especially 18 each have strict rules, and the last digit is the check digit . And we in practical applications for identity verification should strictly so far. Thus IdcardUtilcame into being.

IdcardUtilContinental now supports 15, 18 identity cards, Hong Kong, Macao and Taiwan 10 identity cards.

The main tool of the method include:

  1. isValidCardTo verify the legality of ID card
  2. convert15To18ID 15 rpm 18
  3. getBirthByIdCardGets Birthday
  4. getAgeByIdCardGets Age
  5. getYearByIdCardGets Birthday Year
  6. getMonthByIdCardGet birthday month
  7. getDayByIdCardGets Birthday Day
  8. getGenderByIdCardGet sex
  9. **getProvinceByIdCard**Gets provinces

use

String ID_18 = "321083197812162119";
String ID_15 = "150102880730303";

//是否有效
boolean valid = IdcardUtil.isValidCard(ID_18);
boolean valid15 = IdcardUtil.isValidCard(ID_15);

//转换
String convert15To18 = IdcardUtil.convert15To18(ID_15);
Assert.assertEquals(convert15To18, "150102198807303035");

//年龄
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);

//生日
String birth = IdcardUtil.getBirthByIdCard(ID_18);
Assert.assertEquals(birth, "19781216");

String birth2 = IdcardUtil.getBirthByIdCard(ID_15);
Assert.assertEquals(birth2, "19880730");

//省份
String province = IdcardUtil.getProvinceByIdCard(ID_18);
Assert.assertEquals(province, "江苏");

String province2 = IdcardUtil.getProvinceByIdCard(ID_15);
Assert.assertEquals(province2, "内蒙古");
复制代码

At last

This article is only mentioned some of the tools HuTool in fact, HuTool is a perfect project to realize a lot of Java operation so that we can easily deal with when handling some of the more complex content.

Number of public: "Costa said net thing," the author's home: www.goodsoon.com

Guess you like

Origin juejin.im/post/5e5b84f3e51d452713551e2c