Recently the company came to a batch of interns, ah fan is responsible for taking one. To tell you the truth, this young teacher is very solid in basic skills and very reliable in work.

However, when I reviewed the code recently, FAN found that some of the code logic was a little cumbersome. Fan thought that some of the code could be implemented with some open source tool classes without repeated implementation.

But this is normal, ah Fan just started to write the code is also like this, these years slowly contact with some open source tool classes, gradually accumulated. Now when I write code, I will directly replace the cumbersome logic I implement with utility classes.

So Fan shared a few open source tools she often used with him. After learning them, he called them “666”.

Here, Ah-fan shares some common tools to help students who just started their career. Other programming veteran drivers if there are other useful tool class, welcome to share in the comments section.

Common tool classes in these directions are shared below:

String-related utility classes

In Java, String is probably the most commonly used class, so we usually have a lot of code around String to do some processing.

The JDK provides a String API, but its functions are basic. Usually, we need to combine multiple String methods to complete a business function.

Here’s a look at StringUtils, a utility class provided by Apache.

Maven Pom information is as follows:

Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - lang3 < / artifactId > < version > 3.10 < / version > </dependency>Copy the code

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

Commons-lang is an old version that has not been maintained for a long time.

Commons-lang3 is a version that has been maintained and is recommended to use directly.

Note: If you already have commons-lang on your system, note that it will compile an error if you replace it with commons-lang3. The related class in Commons-lang3 is the same as commons-lang, but the package name is different.

Checks if the string is empty

Check if a string is empty, as everyone has already written:

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

}
Copy the code

Although this code is very simple, to be honest, fan has made null pointer exceptions here before.

With 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 used to determine whether a string is empty.

Stringutils.leftpad (stringutils.leftpad (stringutils.leftpad))"test"Eight,"0");
Copy the code

If the string is empty, it is used frequently. Here you can use the function of IDEA Prefix to directly generate null statement.

String fixed length

This is usually used when the string needs a fixed length, such as a fixed length string as the serial number. If the serial number length is insufficient, 0 is added to the left.

We can use the String#format method here, but we can use it like this:

Stringutils. leftPad(stringutils. leftPad(stringutils. leftPad))"test"Eight,"0");
Copy the code

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

String keyword replacement

StringUtils provides a list of methods that can replace certain keywords:

// Replace all keywords stringutils.replace ("aba"."a"."z")   = "zbz"; // Replace the keyword only once stringutils.replaceonce ("aba"."a"."z")   = "zba"; / / use regular expressions to replace StringUtils. ReplacePattern ("ABCabc123"."[^A-Z0-9]+"."")   = "ABC123"; .Copy the code

String splicing

String concatenation is a common requirement, and an easy way to do this is to loop through the 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 emptyif (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 get the concatenated string directly using the following method:

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

StringUtils can only pass in array concatenation strings, but I prefer set concatenation, so I recommend Guava Joiner.

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, ","); // Omit 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 StringUtils also has 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: Notice the difference between the above two methods.

StringUtils is split into an array, and we can use Guava’s

Splitter splitter = Splitter.on(","); [ab, b, c] splitter.splittolist ("ab,,b,c"); / / ignore the empty string, the output (ab, b, c) splitter. OmitEmptyStrings () splitToList ("ab,,b,c")
Copy the code

There are other common methods in StringUtils that you can check out the API for yourself.

Date-related utility classes

DateUtils/DateFormatUtils

Before JDK8, Java only provided a Date class, usually we need to convert Date to a string according to a certain format, we need to use SimpleDateFormat.

SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date to 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 it is important to note that SimpleDateFormat is not thread-safe and must be used safely in multithreaded environments.

Here powder o recommend Commons – lang3 DateUtils/DateFormatUtils next time tool, the Date and the string conversion solution.

Ps: For fun, do you have many classes called DateUtils in your project? Fan found that our existing projects, multiple modules have this class, each implementation is much the same.

It’s very simple to use:

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 provides time-related functions.

Date now = new Date(); AddDays = dateutils. addDays(now, 1); // dateutils. addMinutes = dateutils. addMinutes(now, 33); Date addSeconds = dateutils. addSeconds(now, -233); Boolean sameDay = dateutils. isSameDay(addDays, addMinutes); If the truncate method is invoked after now is 2020-05-07 22:13:00, the return time is 2020-05-07 00:00:00 Date TRUNCate = DateUtils.truncate(now, Calendar.DATE);Copy the code

JDK8 time class

After JDK8, Java divides date and time into LocalDate and LocalTime, which is more clearly defined. Of course, it also provides a LocalDateTime, which contains date and time. The advantage of these classes over Date is that, like String, they are immutable, thread-safe, and cannot be modified.

Mysql > select DATETIME, DATETIME, DATETIME, DATETIME, DATETIME, DATETIME, DATETIME

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

If we still use the Date type, and if we need to use a new time type, we need to do a related conversion. 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 the current system's default time zone LocalDateTimelocalDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); // LocalDateTime------> Date Specifies the current system default time zone. Date = date.from (localDateTime.atZone(ZoneId.systemDefault()).toInstant());
Copy the code

Next we use LocalDateTime for string formatting.

DateTime = localDatetime. parse(yyyY-MM-DD HH: MM :ss)"The 2020-05-07 22:34:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); / / will LocalDateTime formatted 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, month is very simple:

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

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

LocalDateTime now = LocalDateTime.now(); PlusDays = now.plusdays (1l); // LocalDateTime plusDays = now.plusdays (1l); LocalDateTime minusHours = now.minushours (1l); LocalDateTime minusHours = now.minushours (1l); // There are many other waysCopy the code

In short, JDK8 provides the time class is very easy to use, have not used friends, can try.

Collection/array correlation

Collections and arrays are also frequently used and nullized:

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

}
Copy the code

Ps: Array and Map collections are similar

The above code is as simple to write as string nulling, but it’s also easier to write code that throws a null-pointer exception. Here we can provide utility classes using commons-Collections.

Pom information:

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

Ps: There is also a lower version, artifactId for Commons-collections

We can use CollectionUtils/MapUtils for short judgment.

// List/Setif(collectionUtils.isempty (list)){} // Map, etcif (MapUtils.isEmpty(map)) {
    
}
Copy the code

ArrayUtils under Commons-lang is used to judge array nulls:

// Array nullsif (ArrayUtils.isEmpty(array)) {
    
}
Copy the code

In addition, there are a number of column enhancements to collections, such as quickly adding arrays to existing collections:

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 by yourself. In addition, Guava also provides enhanced Lists/Maps for the operation of sets. You can read the previous article written by Fan: Old driver Fan takes you to play Guava sets.

The I/O

The JDK provides a series of classes that can read files, etc., but Fan finds those classes somewhat arcane and requires a lot of code to implement a small function, and may not get it right.

Apache commons-io library to enhance I/O operations and simplify operations. Pom information:

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

FileUtils- File manipulation utility class

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

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

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

File directory = new File()"E:\\test");
FileUtils.listFiles(directory, new String[]{"txt"}, false);
Copy the code

Read all lines of the file with fileutils.readlines.

// Read all lines of the specified filewhileList<String> lines = fileutils.readlines (fileA)Copy the code

Fileutils. writeLines allows you to write data row by row from a set to text.

List<String> lines = new ArrayList<>(); . FileUtils.writeLines(lines)Copy the code

IOUtils- Tools related to I/O operations

FileUtils is mainly for related files, IOUtils is more for low-level I/O, can quickly read InputStream. In fact, the underlying operation of FileUtils depends on IOUtils.

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

Get 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 InputStream InputStreamin = request.getInputStream();
    for(int len = 0; (len = in.read(buffer)) > 0; ) { baos.write(buffer, 0, len); } b = baos.toByteArray(); baos.close(); String reqMessage = new String(b,"utf-8");
} catch (IOException e) {
  
} finally {
    if(baos ! = null) { try { baos.close(); } catch (IOException e) { } } }Copy the code

The code above is quite complicated. With IOUtils, however, one method is simple:

Byte [] b = ioutils.tobytearray (request.getinputStream ()); byte[] b = ioutils.tobytearray (request.getinputStream ()); // convert input stream information toString resMsg = ioutils.tostring (request.getinputstream ());Copy the code

Ps: InputStream cannot be read repeatedly

timing

Programming sometimes need to count the execution time of the code, of course, the execution of the code is very simple, the end time and the start time can be subtracted.

long start = System.currentTimeMillis(); // Get the start time // other code //... long end = System.currentTimeMillis(); System.out.println(system.out.println ("Program runtime:" + (end - start) + "ms");
Copy the code

While the code is very simple, it is very inflexible, and by default we can only get ms units. If we need to convert 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 is used in much the same way, depending on your situation.

Stopwatch Stopwatch = stopwatch.createstarted (); / / create the timer, but need to invoke the start method start timing / / Stopwatch Stopwatch = a Stopwatch. CreateUnstarted (); // stopWatch.start(); Timeunit.seconds.sleep (2l); System.out.println(stopwatch.Elapsed (timeunit.seconds)); TimeUnit.SECONDS.sleep(2l); IllegalStateException stopWatch.stop (); // Stop the timer before it starts. System.out.println(stopwatch.Elapsed (timeunit.seconds)); Reset () stopwatch.start() 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 we introduced strings, dates, arrays/collections, I/O, timing, and other utility classes to simplify everyday business code. You can give it a try, and I have to say, these tools smell good!

If you like our article, welcome to forward, click to see more people see. Welcome all friends who love technology and learning to join our knowledge planet, we grow together and make progress.

The original link: mp.weixin.qq.com/s/Dh3G0e3Ih…