Skip to content

Apache Commons使用 ​

Apache Commons提供了大量实用的工具类和工具方法,包括Lang、Collections、IO、Codec等工具包。本文详细介绍各工具包的使用方法和最佳实践。

📋 目录 ​

🎯 一、Maven依赖 ​

1.1 添加依赖 ​

xml
<!-- Commons Lang -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

<!-- Commons Collections -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

<!-- Commons IO -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>

<!-- Commons Codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

🎯 二、Commons Lang ​

2.1 StringUtils ​

字符串判断:

java
import org.apache.commons.lang3.StringUtils;

// 判断是否为空
StringUtils.isEmpty("");        // true
StringUtils.isEmpty(null);      // true
StringUtils.isEmpty(" ");       // false

// 判断是否为空白
StringUtils.isBlank("");        // true
StringUtils.isBlank(null);      // true
StringUtils.isBlank(" ");       // true
StringUtils.isBlank("  \t  ");  // true

// 判断是否不为空
StringUtils.isNotEmpty("");     // false
StringUtils.isNotBlank(" ");    // false

字符串处理:

java
// 空值处理
StringUtils.defaultString(null);        // ""
StringUtils.defaultString(null, "默认值"); // "默认值"
StringUtils.defaultIfBlank(null, "默认值"); // "默认值"

// 去除空白
StringUtils.trim("  hello  ");          // "hello"
StringUtils.trimToNull("   ");          // null
StringUtils.trimToEmpty(null);          // ""

// 去除指定字符
StringUtils.strip("  hello  ", " ");    // "hello"
StringUtils.stripStart("  hello", " "); // "hello"
StringUtils.stripEnd("hello  ", " ");   // "hello"

字符串截取:

java
// 截取字符串
StringUtils.substring("hello", 1, 4);        // "ell"
StringUtils.left("hello", 3);                // "hel"
StringUtils.right("hello", 3);               // "llo"
StringUtils.mid("hello", 1, 3);              // "ell"

// 安全截取(防止越界)
StringUtils.substring("hello", 0, 100);      // "hello"

字符串填充:

java
// 左填充
StringUtils.leftPad("123", 5, '0');    // "00123"

// 右填充
StringUtils.rightPad("123", 5, ' ');   // "123  "

// 居中填充
StringUtils.center("123", 7, '*');     // "**123**"

字符串替换:

java
// 替换所有
StringUtils.replace("hello world", "l", "L");  // "heLLo worLd"

// 替换一次
StringUtils.replaceOnce("hello", "l", "L");    // "heLlo"

// 替换多个字符
StringUtils.replaceChars("hello", "le", "xy"); // "hxyyo"

// 删除字符串
StringUtils.remove("hello", "l");              // "heo"
StringUtils.removeAll("hello", "l");           // "heo"

字符串分割和连接:

java
// 分割字符串
String[] parts = StringUtils.split("a,b,c", ",");        // ["a", "b", "c"]
String[] parts2 = StringUtils.split("a  b  c", null);    // ["a", "b", "c"]

// 分割并去除空白
String[] parts3 = StringUtils.splitByCharacterType("ab123cd");
// ["ab", "123", "cd"]

// 连接字符串
String joined = StringUtils.join(new String[]{"a", "b", "c"}, ","); // "a,b,c"
String joined2 = StringUtils.join(Arrays.asList("a", "b", "c"), "-"); // "a-b-c"

字符串比较:

java
// 比较字符串
StringUtils.compare("a", "b");         // -1
StringUtils.compare("b", "a");         // 1
StringUtils.compare("a", "a");         // 0

// 忽略大小写比较
StringUtils.compareIgnoreCase("A", "a"); // 0

// 判断相等
StringUtils.equals("a", "a");          // true
StringUtils.equals(null, null);        // true
StringUtils.equalsIgnoreCase("A", "a"); // true

2.2 ArrayUtils ​

数组操作:

java
import org.apache.commons.lang3.ArrayUtils;

// 判断数组是否为空
ArrayUtils.isEmpty(null);       // true
ArrayUtils.isEmpty(new int[0]); // true
ArrayUtils.isNotEmpty(new int[]{1, 2}); // true

// 添加元素
int[] arr = {1, 2, 3};
int[] added = ArrayUtils.add(arr, 4);           // [1, 2, 3, 4]
int[] added2 = ArrayUtils.add(arr, 1, 5);       // [1, 5, 2, 3, 4]

// 删除元素
int[] removed = ArrayUtils.remove(arr, 1);      // [1, 3]
int[] removed2 = ArrayUtils.removeElement(arr, 2); // [1, 3]

// 查找元素
int index = ArrayUtils.indexOf(arr, 2);         // 1
boolean contains = ArrayUtils.contains(arr, 2); // true

// 数组反转
ArrayUtils.reverse(arr);  // 原地反转

// 数组转换
Integer[] intArray = ArrayUtils.toObject(new int[]{1, 2, 3});
int[] primArray = ArrayUtils.toPrimitive(intArray);

2.3 DateUtils ​

日期工具:

java
import org.apache.commons.lang3.time.DateUtils;

Date date = new Date();

// 日期舍入
Date startOfDay = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
Date startOfHour = DateUtils.truncate(date, Calendar.HOUR_OF_DAY);

// 日期计算
Date addDays = DateUtils.addDays(date, 10);
Date addMonths = DateUtils.addMonths(date, 2);
Date addYears = DateUtils.addYears(date, 1);
Date addHours = DateUtils.addHours(date, 5);

// 日期比较
boolean isSameDay = DateUtils.isSameDay(date1, date2);
boolean isSameInstant = DateUtils.isSameInstant(date1, date2);

// 解析日期
Date parsed = DateUtils.parseDate("2024-01-01", "yyyy-MM-dd");
Date parsed2 = DateUtils.parseDateStrictly("2024-01-01", "yyyy-MM-dd");

🎯 三、Commons Collections ​

3.1 CollectionUtils ​

集合工具:

java
import org.apache.commons.collections4.CollectionUtils;

List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("c", "d", "e");

// 判断是否为空
boolean isEmpty = CollectionUtils.isEmpty(list1);

// 并集
Collection<String> union = CollectionUtils.union(list1, list2);
// 结果:[a, b, c, d, e]

// 交集
Collection<String> intersection = CollectionUtils.intersection(list1, list2);
// 结果:[c]

// 差集
Collection<String> subtract = CollectionUtils.subtract(list1, list2);
// 结果:[a, b]

// 判断是否包含任意元素
boolean containsAny = CollectionUtils.containsAny(list1, list2);

// 判断是否包含所有元素
boolean containsAll = CollectionUtils.containsAll(list1, list2);

// 过滤集合
CollectionUtils.filter(list1, s -> s.startsWith("a"));

// 转换集合
Collection<String> transformed = CollectionUtils.collect(
    list1, 
    String::toUpperCase
);

// 查找元素
String found = CollectionUtils.find(list1, s -> s.length() > 1);

// 计数
int count = CollectionUtils.countMatches(list1, s -> s.length() == 1);

3.2 MapUtils ​

Map工具:

java
import org.apache.commons.collections4.MapUtils;

Map<String, Integer> map = new HashMap<>();

// 判断Map是否为空
boolean isEmpty = MapUtils.isEmpty(map);

// 安全获取值
Integer value = MapUtils.getInteger(map, "key", 0);  // 默认值0

// 多级Map访问
Map<String, Map<String, Integer>> nestedMap = new HashMap<>();
Integer nestedValue = MapUtils.getInteger(nestedMap, "key1", "key2", 0);

// Map反转(键值互换)
Map<Integer, String> reversed = MapUtils.invertMap(map);

🎯 四、Commons IO ​

4.1 FileUtils ​

文件操作:

java
import org.apache.commons.io.FileUtils;
import java.io.File;

// 读取文件
File file = new File("data.txt");
String content = FileUtils.readFileToString(file, "UTF-8");

// 读取文件为字节数组
byte[] bytes = FileUtils.readFileToByteArray(file);

// 按行读取
List<String> lines = FileUtils.readLines(file, "UTF-8");

// 写入文件
FileUtils.writeStringToFile(file, "content", "UTF-8");
FileUtils.writeByteArrayToFile(file, bytes);

// 追加内容
FileUtils.writeStringToFile(file, "追加内容", "UTF-8", true);

// 复制文件
FileUtils.copyFile(sourceFile, destFile);

// 复制目录
FileUtils.copyDirectory(sourceDir, destDir);

// 移动文件
FileUtils.moveFile(sourceFile, destFile);

// 删除文件或目录
FileUtils.deleteQuietly(file);  // 静默删除,不抛异常
FileUtils.forceDelete(file);    // 强制删除

// 文件比较
boolean equal = FileUtils.contentEquals(file1, file2);

// 计算文件大小
long size = FileUtils.sizeOf(file);
long size2 = FileUtils.sizeOfDirectory(dir);

// 清理目录(删除目录内容,保留目录)
FileUtils.cleanDirectory(dir);

4.2 IOUtils ​

IO工具:

java
import org.apache.commons.io.IOUtils;

// 读取输入流
InputStream is = new FileInputStream("file.txt");
String content = IOUtils.toString(is, "UTF-8");

// 读取为字节数组
byte[] bytes = IOUtils.toByteArray(is);

// 读取为列表
List<String> lines = IOUtils.readLines(is, "UTF-8");

// 写入输出流
OutputStream os = new FileOutputStream("output.txt");
IOUtils.write("content", os, "UTF-8");

// 复制流
IOUtils.copy(inputStream, outputStream);

// 关闭流
IOUtils.closeQuietly(inputStream);  // 静默关闭,忽略异常
IOUtils.closeQuietly(inputStream, outputStream);  // 关闭多个流

🎯 五、Commons Codec ​

5.1 编码解码 ​

Base64编码:

java
import org.apache.commons.codec.binary.Base64;

String str = "Hello World";

// Base64编码
byte[] encoded = Base64.encodeBase64(str.getBytes());
String encodedStr = Base64.encodeBase64String(str.getBytes());
// 结果:"SGVsbG8gV29ybGQ="

// Base64解码
byte[] decoded = Base64.decodeBase64(encodedStr);
String decodedStr = new String(decoded);
// 结果:"Hello World"

// URL安全的Base64
String urlSafe = Base64.encodeBase64URLSafeString(str.getBytes());

MD5和SHA:

java
import org.apache.commons.codec.digest.DigestUtils;

String str = "Hello World";

// MD5
String md5 = DigestUtils.md5Hex(str);

// SHA256
String sha256 = DigestUtils.sha256Hex(str);

// SHA512
String sha512 = DigestUtils.sha512Hex(str);

// 文件MD5
String fileMd5 = DigestUtils.md5Hex(new FileInputStream("file.txt"));

其他编码:

java
// URL编码
String encoded = URLCodec.encodeUrl(null, "hello world");
// 结果:"hello+world"

// Hex编码
String hex = Hex.encodeHexString("hello".getBytes());
// 结果:"68656c6c6f"

📖 学习资源 ​

官方文档 ​

✅ 学习检查清单 ​

  • [ ] 已掌握StringUtils的使用
  • [ ] 已掌握ArrayUtils的使用
  • [ ] 已了解CollectionUtils的使用
  • [ ] 已掌握FileUtils和IOUtils的使用
  • [ ] 已了解编码解码工具的使用

上一章节:Guava工具包使用
下一章节:Jackson使用指南
返回目录:代码规范