Home  >  Article  >  Java  >  Organizing and using jar packages commonly used in Java development

Organizing and using jar packages commonly used in Java development

angryTom
angryTomforward
2019-11-29 13:16:172246browse

This article organizes my own commonly used jar packages and commonly used API records in Java development.

Organizing and using jar packages commonly used in Java development

1. common-lang3

Introduction: A jar package that is now the most commonly used, encapsulating many commonly used tool packages

(Recommended video: java video tutorial)

Dependency:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

The main common classes are as follows:

Array Tool class ArrayUtils

Date tool class DateUtils DateFormatUtils

String tool class StringUtils

Number tool class NumberUtils

Boolean tool class BooleanUtils

Reflection related tool classes FieldUtils, MethodUtils, MemberUtils, TypeUtils, ConstructorUtils

Object tool class ObjectUtils

Serialization tool class SerializationUtils

API introduction

Here I will only introduce a few frequently used tool classes and methods, ArrayUtils, StringUtils, NumberUtils, DateUtils. For others, please check the official API documentation

1.ArrayUtils

##cloneCopy arrayaddAll##removeAlltoObjectindexOflastIndexOf containsisEmptyisNotEmptyreversesubarraytoArraytoMap
Method name Description
add
remove

The second parameter is passed in the subscript to be deleted (Multiple subscripts can be specified)
Convert the value (int[], double[]) to the packaging class (Int[], Double[] )
Search in order in the array and find the first index that satisfies the corresponding value
Search the array in order and find the last subscript that satisfies the corresponding value
Whether the array contains a certain value
Determine whether the array is empty
Determine whether the array is not empty
Array reversal
Specify the interval to intercept the array. The interval is a half-open interval and does not contain At the end
Receives multiple objects and converts these objects into arrays of corresponding types
Convert a two-dimensional array to a Map
2.NumberUtils

Method name##minCompare three numbers , return the minimum value or compare several specified numbers, return the minimum value max Compare three numbers, return the maximum value or compare several specified numbers, Return the maximum valuecreateIntCreate a value of the corresponding type from the incoming String, createDouble, createFloat...toIntConvert the specified string to Int type. You can choose to specify a default value. If the string is null, the default value will be returned. In addition, there are also toDouble, toLong... and so on. Different types of methodscompareCompare the size of two values ​​of the same typeisDigits Determine whether the string only contains numbersisParsableDetermine whether the string can be converted to Long, Int and other types isNumberDetermine whether the string is a numerical value (0x, equal decimal value starting with 0X)3.DateUtils


Description

Method nameDescription##parseDateConvert Date object For the string Determine whether two Dated objects are on the same day Determine whether two Dated objects are on the same dayAdd the specified hour to the specified Date object. In addition, there are addMonth, addDay.. wait
isSameDay
isSameDay
addHour

DateFormatUtils, as its name suggests, is used to convert time into a string, so I won’t say more here

4.StringUtils

will be added automatically ##removeEndIgnoreCase is the same as the above Same, ignore caseremoveStartOpposite of the aboveremoveRemove string The specified content in the string, such as remove("hello","l")="heo"removeIgnoreCaseRemove the specified content in the string, such as remove( "hello","l")="heo"stripClear the characters specified at the beginning and end of the string (the second parameter is null, used to Remove spaces at the beginning and end of the string), such as strip(" abcxy","xy")=" abc",strip(" abcxy","yx")=" abc"stripStartClear the specified characters at the beginning of the stringstripEndClear the specified characters at the end of the string

二、common-io

简介:常用的IO流工具包

<!-- https://mvnrepository.com/artifact/commons-io/commons-io --><dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version></dependency>

我们主要关心的就是Utils后缀的那几个类即可,可以看到,common-io库提供了FileUtils,FileSystemUtils,FileNameUtils,FileFilterUtils,IOUtils

FileUtils

● 写出文件

● 读取文件

● 创建一个有父级文件夹的文件夹

● 复制文件和文件夹

● 删除文件和文件夹

● URL转文件

● 通过过滤器和扩展名来筛选文件和文件夹

● 比较文件内容

● 文件最后修改时间

● 文件校验

FileSystemUtils

关于文件系统的相关操作,如查看C盘的大小,剩余大小等操作

IOUtils

字面意思,是封装了IO流的各种操作的工具类

三、Log4j

简介:Log4J 是 Apache 的一个开源项目,通过在项目中使用 Log4J,我们可以控制日志信息输出到控制台、文件、GUI 组件、甚至是数据库中。

我们可以控制每一条日志的输出格式,通过定义日志的输出级别,可以更灵活的控制日志的输出过程,方便项目的调试。

依赖:

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

结构

Log4J 主要由 Loggers (日志记录器)、Appenders(输出端)和 Layout(日志格式化器)组成。

其中Loggers 控制日志的输出级别与日志是否输出;

Appenders 指定日志的输出方式(输出到控制台、文件等);

Layout 控制日志信息的输出格式。

日志级别:

Method name Description
join Connect the specified array into a string. And add the specified dividing characters
containOnly Whether the string only contains a certain string
substringBefore Intercept the content before the specified string
substringAfter Intercept the content after the specified string (excluding the specified string)
substringBetween Intercept the content of a certain range of the string, such as substringBetween("abcde","a","e")="bcd"
difference Compares two strings and returns the different contents of the two strings. For details, please see the example given in the API document
isBlank Determine whether the string is blank, null, "", " "The three results are all true
isEmpty Determine whether the string is empty (as long as it is not is null, or the length of the incoming String object is not 0, it means true)
countMatches Determine whether the specified string appears in a certain string Times
deleteWhitespace Delete spaces in the string
defaultIfBlank If the string is blank , returns a specified default value (null or a String)
defaultIfEmpty If the string is empty, returns a specified default value (null or A certain String)
capitalize Capitalize the first letter of the specified string
abbreviate Convert the last three digits of the specified string to...
swapCase Reverse the case of letters in the string, such as aBc becomes AbC
lowerCase Convert all the letters in the string to lowercase
upperCase Convert all the letters in the string to lowercase Convert to uppercase
left Take the left few characters of the string, such as left("hello",3)="hel", right is the opposite
leftPad If the length of the string is not enough, use the specified characters to fill the specified string, such as leftPad("hel",5,"z")="zzhel", The rightPad method is the opposite
prependIfMissing If the specified string does not start with a certain string, the beginning will be added automatically, such as prependIfMissing("hello","li" )="lihello"
prependIfMissing If the specified string does not start with a certain string (ignoring case), the beginning
getCommonPrefix Get the same starting content of multiple strings, and receive parameters for multiple strings
removeEnd Delete The end of the string (satisfied that it ends with a certain piece of content), such as removeEnd("hello","llo")="he"
级别 说明
OFF 最高日志级别,关闭左右日志
FATAL 将会导致应用程序退出的错误
ERROR 发生错误事件,但仍不影响系统的继续运行
WARN 警告,即潜在的错误情形
INFO 一般和在粗粒度级别上,强调应用程序的运行全程
DEBUG 一般用于细粒度级别上,对调试应用程序非常有帮助
ALL 最低等级,打开所有日志记录

我们主要使用这四个:Error>Warn>Info>Debug

使用

我们可以使用两种方式来运行Log4j,一种是java代码方式,另外一种则是配置文件方式

例子(Java方式)

public class Log4JTest {
    public static void main(String[] args) {   
        //获取Logger对象的实例(传入当前类)         
        Logger logger = Logger.getLogger(Log4JTest.class);
        //使用默认的配置信息,不需要写log4j.properties
        BasicConfigurator.configure();
        //设置日志输出级别为WARN,这将覆盖配置文件中设置的级别,只有日志级别低于WARN的日志才输出
        logger.setLevel(Level.WARN);
        logger.debug("这是debug");
        logger.info("这是info");
        logger.warn("这是warn");
        logger.error("这是error");
        logger.fatal("这是fatal");
    }
}

例子(配置文件方式)

上面的例子,我们想要实现打印Log,但是每次都要写一遍,浪费时间和精力,所以,Log4j提供了另外一种方式来配置好我们的信息

创建一个名为log4j.properties的文件,此文件需要放在项目的根目录(约定),如果是maven项目,直接放在resources文件夹中即可

log4j.properties

#控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#log jdbc
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=WARN
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
#log mybatis设置
#log4j.logger.org.apache.ibatis=DEBUG
log4j.logger.org.apache.ibatis.jdbc=error
log4j.logger.org.apache.ibatis.io=info
log4j.logger.org.apache.ibatis.datasource=info
#springMVC日志
log4j.logger.org.springframework.web=WARN
# 文件输出配置
log4j.appender.A = org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File = D:/log.txt #指定日志的输出路径
log4j.appender.A.Append = true
log4j.appender.A.Threshold = DEBUG
log4j.appender.A.layout = org.apache.log4j.PatternLayout #使用自定义日志格式化器
log4j.appender.A.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n #指定日志的输出格式
log4j.appender.A.encoding=UTF-8 #指定日志的文件编码
#指定日志的输出级别与输出端
log4j.rootLogger=DEBUG,Console,A
#指定某个包名日志级别(不能超过上面定义的级别,否则日志不会输出)
log4j.logger.com.wan=DEBUG

之后使用的话就比较简单了

//Logger的初始化(这个推荐定义为全局变量,方便使用)
Logger logger = Logger.getLogger(Log4JTest.class);
//输出Log
logger.info("这是info");

四、lombok

简介:平常我们创建实体类的时候,需要get/set方法,极其麻烦,虽然IDEA等IDE都是有提供了快捷生成,不过,最好的解决方法还是省略不写

而lombok就是这样的一个框架,实现省略get/set方法,当然,lombok的功能不只有此,还有equal,toString方法也可以由此框架自动生成

lombok的原理是使用注解,之后就会在编译过程中,给Class文件自动加上get/set等方法

不过IDEA似乎无法识别,代码检查还是会报错,所以,使用IDEA的时候还得安装一个插件,在plugin搜索lombok,之后安装重启即可,如图

Organizing and using jar packages commonly used in Java development

之后为Java项目添加依赖

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
    <scope>provided</scope>
</dependency>

使用示例

1.实体类省略get/set

估计Kotlin中的data关键字就是参照着lombok实现的

//这里我们只需要为类添加Data注解,就会自动生成对应属性的get/set方法,toString,equal等方法
@Data
public class User {
    private String username;
    private String password;
}

2.需要无参构造以及get/set方法

@Getter
@Setter
@NoArgsConstructor
public class User {
    private String username;
    private String password;
}

3.链式调用set方法

@Data
@Accessors(chain = true)
public class User {
    private String username;
    private String password;
}
//使用
User user = new User();
user.setUsername("helo").setPassword("123");

4.参数不为空

//如果调用此方法,就会抱一个空指针错误
public String print(@NotNull String str){
    ...
}

5.只需要toString

@ToString(callSuper=true, includeFieldNames=true)
public class User {
    private String username;
    private String password;
    //省略的get/set方法
}

6.builder模式创建实体类对象

@Data
@Builder
public class User {
    private String username;
    private String password;
}
//使用
User user1 = User.builder().username("user1").password("123").build();

7.工具类

@UtilityClass
public class MyUtils{
    //会将此方法自动转为静态方法
    public void print(String str){
        ...
    }
}
//使用
MyUtils.print("hello");

8.自动关闭流

public static void main(String[] args) throws Exception {
    //使用Cleanup会自动调用close方法
    @Cleanup InputStream in = new FileInputStream(args[0]);
    @Cleanup OutputStream out = new FileOutputStream(args[1]);
    byte[] b = new byte[1024];
    while (true) {
        int r = in.read(b);
        if (r == -1) break;
        out.write(b, 0, r);
    }
}

9.省略Logger时的初始化

@Log4j
@Log
public class User{
    //会自动添加此语句
    //Logger logger = Logger.getLogger(User.class);
    ...
}

本文来自php中文网,java教程栏目,欢迎学习!  

The above is the detailed content of Organizing and using jar packages commonly used in Java development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete