Recently, the company has a group of interns, and the little black brother is responsible for one. To tell the truth, this young teacher’s basic skills are very solid, work is very reliable, deep black brother true.

However, when reviewing the code recently, the little black brother found that some of the code logic is a little cumbersome, some of the code little black brother seems to be able to use some open source tools class implementation, do not need to repeat their own implementation.

But this is normal, the little black brother just entered the line of writing code is also like this, these years slowly contact with some open source tools class, gradually accumulated. Only now do I replace the cumbersome logic I implemented with utility classes.

So the little black brother to share a few of their own commonly used open source tools class, little teacher brother after learning: “666”.

Here the little black brother to introduce jade, share a few commonly used tools class, hope to help the new industry students. If you have any other useful classes, please share them in the comments section.

Common tool classes in these directions are mainly shared below:

String related utility class

In Java, String is probably one of the most commonly used classes every day, and we usually have a lot of code around String to do some processing.

Although the JDK provides a number of String apis, the functions are relatively basic. Usually, we need to combine multiple String methods to complete a business function.

Here is an introduction to StringUtils, a tool class provided by Apache.

Maven Pom information:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.10</version>
</dependency>

Copy the code

There are two versions of Commons -lang, Commons -lang3 and Commons -lang.

Commons-lang is an older version and has not been maintained for a long time.

Commons-lang3 is an ongoing release, and it is recommended to use it directly.

Note: If your system already has Commons -lang, note that replacing it with Commons -lang3 will result in a compilation error. The related classes in Commons -lang3 are the same as Commons -lang, but the package names are different.

Determines whether the string is empty

Check whether the string is empty, as everyone has written:

if (null == str || str.isEmpty()) {

}
Copy the code

Although this code is very simple, to be honest, the little nigger has committed null pointer exceptions here before.

Using StringUtils, the above code can be replaced with the following:

if (StringUtils.isEmpty(str)) {

}
Copy the code

StringUtils also has an internal method, isBlank, which is also used to determine whether a string is empty. The two methods are similar to each other. The main differences are as follows:

// If the string is all Spaces,
StringUtils.isBlank("")       = true;
StringUtils.isEmpty("")       = false;Copy the code

To determine whether the string is empty, the frequency is very high, here you can use the IDEA Prefix function, input directly to generate a null statement.

String fixed length

This is usually used when a string of fixed length is required. For example, a string of fixed length is required as a serial number. If the length of the serial number is insufficient, add 0 to the left.

String#format = String#format = String#format

// The string contains a fixed length of 8 characters
StringUtils.leftPad("test".8."0");
Copy the code

There is also StringUtils#rightPad, which is the opposite of the above method.

String keyword replacement

StringUtils provides a list of methods to replace certain keywords:

// Replace all keywords by default
StringUtils.replace("aba"."a"."z")   = "zbz";
// Replace the keyword only once
StringUtils.replaceOnce("aba"."a"."z")   = "zba";
// Use regular expression substitution
StringUtils.replacePattern("ABCabc123"."[^A-Z0-9]+"."")   = "ABC123"; .Copy the code

String concatenation

String concatenation is a common requirement. A simple way to do this is to loop through concatenation using StringBuilder:

String[] array = new String[]{"test"."1234"."5678"};
StringBuilder stringBuilder = new StringBuilder();

for (String s : array) {
    stringBuilder.append(s).append(";");
}
// Prevent the final concatenation string from being empty
if (stringBuilder.length() > 0) {
    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
System.out.println(stringBuilder.toString());
Copy the code

Business code above is not too difficult, but you need to pay attention to the code above is very easy to get wrong, easy to sell StringIndexOutOfBoundsException.

Here we can directly retrieve the concatenated string using the following method:

StringUtils.join(["a"."b"."c"].",")    = "a,b,c"
Copy the code

StringUtils can only pass array concatenation strings, but I prefer collection concatenation, so I recommend Guava’s Joiner.

The example code is as follows:

String[] array = new String[]{"test"."1234"."5678"};
List<String> list=new ArrayList<>();
list.add("test");
list.add("1234");
list.add("5678");
StringUtils.join(array, ",");

// Comma delimiter, skip null
Joiner joiner=Joiner.on(",").skipNulls();
joiner.join(array);
joiner.join(list);
Copy the code

String splitting

With string concatenation, there is a need to split strings, and likewise with StringUtils there is a way to split strings.

StringUtils.split("a.. b.c".'. ')   = ["a"."b"."c"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("a.. b.c".".") = ["a".""."b"."c"]
Copy the code

Ps: Pay attention to the difference between the above two methods.

StringUtils is an array, so we can use Guava’s

Splitter splitter = Splitter.on(",");
// Return a List, result: [ab,, b, c]
splitter.splitToList("ab,,b,c");
// Ignore the empty string and print [ab, b, c]
splitter.omitEmptyStrings().splitToList("ab,,b,c")
Copy the code

There are other common methods inside StringUtils that you can check out for yourself.

Date-related utility class

DateUtils/DateFormatUtils

Before JDK8, Java only provided a Date class. Normally, we need to convert a Date to a string in a certain format. We need to use SimpleDateFormat.

SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date transfer string
simpleDateFormat.format(new Date());
// String to Date
simpleDateFormat.parse("The 2020-05-07 22:00:00");
Copy the code

The code is simple, but the thing to notice here is that SimpleDateFormat is not thread-safe, so you have to be careful in a multi-threaded environment.

Here the little black brother recommended Commons – lang3 DateUtils/DateFormatUtils next time tool, the Date and the string conversion solution.

Ps: Just for fun, do you have multiple classes called DateUtils in your project? The little black brother found that we have existing project, several modules have this class, each implementation is very similar.

How to use it is very simple:

// Convert Date to string
DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
// String to Date
DateUtils.parseDate("The 2020-05-07 22:00:00"."yyyy-MM-dd HH:mm:ss");
Copy the code

In addition to format conversion, DateUtils also provide functionality related to time calculation.

Date now = new Date();
// Date + 1 day
Date addDays = DateUtils.addDays(now, 1);
// Date = 33 minutes
Date addMinutes = DateUtils.addMinutes(now, 33);
// Date = 233 seconds
Date addSeconds = DateUtils.addSeconds(now, -233);
// Determine whether Wie is the same day
boolean sameDay = DateUtils.isSameDay(addDays, addMinutes);
// Filter the time seconds, if now is 2020-05-07 22:13:00 after calling the truncate method
Return time 2020-05-07 00:00:00
Date truncate = DateUtils.truncate(now, Calendar.DATE);
Copy the code

JDK8 time class

After JDK8, Java divides the date and time into two parts: LocalDate and LocalTime. Of course, Java also provides a LocalDateTime, which contains the date and time. These classes have the advantage over Date in that they, like String, are immutable, thread-safe, and cannot be modified.

Mysql > select * from ‘DATE’ where ‘DATE’ = ‘DATE’ and ‘TIME’ = ‘DATETIME

Now ORM frameworks such as MyBatis support LocalDate and JDBC time type conversion, so you can directly define the actual type of the time field to JDK8 time type, and then related conversion.

If the Date type is still used, we need to convert it to the new time type. To convert between the two, which is a little more complicated, we need to specify the current time zone.

Date now = new Date();
// Date-----> LocalDateTime Specifies that the current system default time zone is used
LocalDateTime localDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// LocalDateTime------> Date Specifies the current system default time zone
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
Copy the code

Next we use LocalDateTime for string formatting.

// Set the conversion time to YYYY-MM-dd HH: MM :ss
LocalDateTime dateTime = LocalDateTime.parse("The 2020-05-07 22:34:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// Format LocalDateTime as a string
String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
Copy the code

In addition, we use LocalDateTime to get the current time, year, and month:

LocalDateTime now = LocalDateTime.now();
/ / year
int year = now.getYear();
/ / month
int month = now.getMonthValue();
/ /,
int day = now.getDayOfMonth();
Copy the code

Finally, we can use LocalDateTime to add or subtract the date and get the time of the next day:

LocalDateTime now = LocalDateTime.now();
// Add one day to the current time
LocalDateTime plusDays = now.plusDays(1l);
// The current time is reduced by one hour
LocalDateTime minusHours = now.minusHours(1l);
// There are many other methods
Copy the code

In short, the time class provided by JDK8 is very easy to use.

Collection/array correlation

Collections and arrays are often used and nulled:

if (null == list || list.isEmpty()) {

}
Copy the code

Ps: Arrays and Map collections are similar

The above code is as simple to write as string nulls, but it’s also easier to write code that throws a null pointer exception. Here we can provide the utility class using Commons-collections.

Pom information:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</vesion>
</dependency>
Copy the code

Ps: There is also an earlier version of artifactId called Commons-collections

We can use CollectionUtils/MapUtils for null judgment.

// List/Set is null
if(CollectionUtils.isEmpty(list)){

}
// Map, etc
if (MapUtils.isEmpty(map)) {
    
}
Copy the code

ArrayUtils: ArrayUtils: ArrayUtils: ArrayUtils

// The array is null
if (ArrayUtils.isEmpty(array)) {
    
}
Copy the code

There are also a number of ways to enhance a collection, such as quickly adding an array to an existing collection:

List<String> listA = new ArrayList<>();
listA.add("1");
listA.add("2");
listA.add("3");
String[] arrays = new String[]{"a"."b"."c"};
CollectionUtils.addAll(listA, arrays);
Copy the code

If you are interested in other methods, you can study them on your own. In addition, Guava also provides Lists/Maps, which can be used to enhance the operation of collections. For this, see “Old driver, Little Black Man takes you to play with Guava collections”.

The I/O

The JDK provides a series of classes to read files, etc., but the class is a bit obscure. It takes a lot of code to implement a small function, and it may not get it right.

The commons-IO library provided by Apache is recommended to enhance AND simplify I/O operations. Pom information:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
Copy the code

Fileutills – File manipulation tool class

The file manipulation utility class provides a series of methods that allow us to read and write files quickly.

Fast implementation file/folder copy operation, FileUtils copyDirectory/FileUtils. Used by copyFile

// Copy the file
File fileA = new File("E:\\test\\test.txt");
File fileB = new File("E:\\test1\\test.txt");
FileUtils.copyFile(fileA,fileB);
Copy the code

Use fileutils. listFiles to get all the files in the specified folder

// Find the files in the specified folder according to the specified file suffix such as Java, TXT, etc
File directory = new File("E:\\test");
FileUtils.listFiles(directory, new String[]{"txt"}, false);
Copy the code

Use fileutils. readLines to read all lines of the file.

// Read all lines of the specified file without using the while loop to read the stream
List<String> lines = FileUtils.readLines(fileA)
Copy the code

Where there is read, there is write. You can use Fileutils. writeLines to directly write the data in the set, line by line, to text.

// Can write text line by line
List<String> lines = newArrayList<>(); . FileUtils.writeLines(lines)Copy the code

Ioutills -i /O operation related tools

FileUtils is used to operate related files. IOUtils is more for low-level I/O. It can read InputStream quickly. In fact, the underlying operation dependency of FileUtils is IOUtils.

IOUtils can be used in a comparative trial scenario, such as payment scenario, HTTP asynchronous notification scenario. If we use the NATIVE JDK method to write:

Get the asynchronous notification content from the Servlet

byte[] b = null;
ByteArrayOutputStream baos = null;
String respMsg = null;
try {
    byte[] buffer = new byte[1024];
    baos = new ByteArrayOutputStream();
  	// Get the input stream
    InputStream in = request.getInputStream();
    for (int len = 0; (len = in.read(buffer)) > 0;) { baos.write(buffer,0, len);
    }
    b = baos.toByteArray();
    baos.close();
  	// Convert the byte array to a string
    String reqMessage = new String(b, "utf-8");
} catch (IOException e) {
  
} finally {
    if(baos ! =null) {
        try {
            baos.close();
        } catch (IOException e) {
           
        }
    }
}
Copy the code

The above code is quite complicated. But let’s use IOUtils, a simple way to do this:

// Output all input stream information to the byte array
byte[] b = IOUtils.toByteArray(request.getInputStream());
// Convert the input stream information to a string
String resMsg = IOUtils.toString(request.getInputStream());
Copy the code

Ps: InputStream cannot be read repeatedly

timing

Sometimes you need to count the execution time of your code. Of course, executing your code is as simple as subtracting the end time from the start time.

long start = System.currentTimeMillis();   // Get the start time

// Other code
/ /...
long end = System.currentTimeMillis(); // Get the end time

System.out.println("Program runtime:" + (end - start) + "ms");
Copy the code

Although the code is simple, it is very inflexible. By default, we can only get ms units. If we want to convert them to seconds or minutes, we need to calculate them separately.

Here we introduce the Guava Stopwatch timing tool class, with the help of his statistics program execution time, the use of very flexible.

Commons-lang3 and Spring-core also have this utility class, which can be used in much the same way, depending on the situation.

// Start the timer immediately after creation, if you want to start the timer actively
Stopwatch stopwatch = Stopwatch.createStarted();
// Create a timer, but you need to call the start method to start the timer
// Stopwatch stopwatch = Stopwatch.createUnstarted();
// stopWatch.start();
// Emulating other code takes time
TimeUnit.SECONDS.sleep(2L);

// The current elapsed time
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));;

TimeUnit.SECONDS.sleep(2L);

Calling stop when a timer has not started will throw an IllegalStateException
stopwatch.stop();
// Collect the total time again
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));;
If you want to start from 0 again, you need to call stopwatch.reset().
stopwatch.start();
TimeUnit.SECONDS.sleep(2L);
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));
Copy the code

The output is:

2
4
6
Copy the code

conclusion

Today, the little black brother introduced the string, date, array/collection, I/O, timing and other tools, simplify the daily business code. You can try after reading, have to say, these tools are really fragrant!

Welcome to pay attention to my public number: procedure, get daily dry goods push. If you are interested in my topics, you can also follow my blog: studyidea.cn