介绍

官网:https://commons.apache.org/

Apache Commons 是一个开源的 Java 项目,旨在提供一组通用的、可复用的 Java 组件。这些组件涵盖了多个领域,包括字符串操作、输入输出、集合操作、数学计算、命令行解析等。

版本

commons-lang commons-lang3 是两个不同的库。尽管它们都与 Apache Commons 有关,但它们是不同的项目,有不同的功能和版本。

  • commons-lang: 是Apache Commons早期的一个语言处理库,用于简化 Java代码。它包含许多有用的工具类,例如字符串操作、数组操作、集合操作等。
  • commons-lang3: 是 commons-lang 的后续版本,也是 Apache Commons的一部分。它提供了许多改进和新功能,并继续致力于简化 Java 代码。这个库是更现代的,并被认为是 commons- ang的替代品。在许多情况下,如果项目需要更新库,开发人员会从 commons-lang 迁移到 commons-lang3

使用

引入依赖

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

集成与扩展

commons-lang可以与其他的Apache Commons项目很好地结合使用。比如与Commons IO一起使用时,它可以提供文件操作的FileUtils封装。

<dependency>
   <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
   <version>2.13.0</version>
</dependency>

常用包、工具

常用类/工具

描述

示例用法

commons-lang

StringUtils

提供了字符串处理的工具方法,如空字符串判断、字符串连接、缩进等。

StringUtils.isEmpty(str);


NumberUtils

提供了处理数字的工具方法,如解析数字、比较数字大小等。

NumberUtils.isDigits(str);


ArrayUtils

提供了对数组的操作,如添加、删除元素,查找元素等。

ArrayUtils.contains(arr, value);


DateUtils

提供了日期操作的工具方法,支持日期格式化、解析、计算等。

DateUtils.addDays(date, 7);

commons-io

FileUtils

提供了文件和目录的操作,如复制文件、删除目录、列出文件等。

FileUtils.copyFile(srcFile, destFile);


IOUtils

提供了处理输入输出流的工具方法,如关闭流、将流转换为字符串等。

IOUtils.toString(inputStream, charset);


FilenameUtils

提供了对文件名的处理,如获取文件扩展名、合并路径等。

FilenameUtils.getExtension(filename);

commons-collections

CollectionUtils

提供了集合操作的工具方法,如合并集合、查找元素等。

CollectionUtils.union(list1, list2);


MapUtils

提供了对 Map 的一些操作,如转换 Map 为字符串、获取默认值等。

MapUtils.getString(map, key,defaultValue);

commons-beanutils

BeanUtils

提供了对 Java Bean 的操作,如复制属性、获取属性值等。

CommandLineParserparser = new DefaultParser();

CommandLine cmd = parser.parse(options, args);

commons-cli

CommandLine

提供了命令行解析的工具,用于解析命令行参数。

CommandLineParser parser = newDefaultParser();

CommandLine cmd =parser.parse(options, args);

commons-math

MathUtils

提供了一些数学相关的工具方法,如阶乘、组合等。

MathUtils.factorial(5);

commons-codec

DigestUtils

提供了消息摘要算法的工具方法,如 MD5、SHA 等。

DigestUtils.md5Hex(data);


Base64

提供了 Base64 编码解码的工具方法。

Base64.encodeBase64String(data);

commons-validator

Validator

提供了一些验证输入数据的工具方法,如邮箱格式验证、URL 验证等。

Validator.isEmail(email);

学习资源

继续深入了解commons-lang,你可以参考以下资源:

官方文档: https://commons.apache.org/proper/commons-lang/ GitHub 仓库: https://github.com/apache/commons-lang 各种技术博客、教程和在线课程 掌握 Apache Commons Lang确实可以让Java开发变得更加高效和愉快。希望这篇文章能够作为你使用这个库的起点。