SuperAPI AI Directory

commons-patterns

General & other

View repository

Updated 10-15 21:48

About this skill

Apache Commons best practice patterns

Source: Commons Home | Lang3 User Guide | IO Description

Capability Boundaries

✅ Strong Suits

  1. StringUtils null-checking patterns — precise semantic choice among isEmpty vs isBlank vs defaultString
  2. Commons IO file operations — FileUtils read/write/copy / IOUtils stream operations / LineIterator line by line
  3. Commons Collections4 — CollectionUtils/MultiValuedMap/MapUtils
  4. RandomStringUtils — generate random strings (verification codes/Tokens/temporary passwords)
  5. Validate — parameter validation (note: since 3.0 throws NullPointerException instead of IllegalArgumentException)

❌ Out of Scope

  1. Chinese-specific features (ID card/Pinyin) → hutool-patterns
  2. Immutable collections/cache/EventBus → guava-patterns
  3. Bean mapping/JSON → mapstruct-patterns/jackson-patterns

Commons vs Guava vs Hutool selection table

Scenario Commons Guava Hutool Preferred choice
String null checking/truncation/padding ⭐⭐⭐ ⭐⭐ ⭐⭐⭐ Any (team convention)
File copy/delete/read lines ⭐⭐⭐ ⭐ ⭐⭐ Commons IO
Filename/path handling ⭐⭐⭐ — ⭐⭐ Commons IO
Collection operations (intersection/union/difference) ⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐ Any
Date handling (legacy Date) ⭐ — ⭐⭐⭐ Java8 Time
Random strings ⭐⭐⭐ — ⭐⭐ Commons Lang3
HTML/XML escaping ⭐⭐⭐ — ⭐ Commons Lang3
Math/statistics ⭐⭐⭐ — ⭐ Commons Math

Core patterns

Pattern 1: StringUtils precise null-checking semantics

// ✅ isEmpty: null 或 "" → true (不含空格)
StringUtils.isEmpty(null);    // true
StringUtils.isEmpty("");      // true
StringUtils.isEmpty(" ");     // false ← 注意!
StringUtils.isEmpty("abc");   // false

// ✅ isBlank: null 或 空白字符 → true
StringUtils.isBlank(null);    // true
StringUtils.isBlank("");      // true
StringUtils.isBlank(" ");     // true ← 含空格也true
StringUtils.isBlank("abc");   // false

// ✅ 选择规则: 表单验证用isBlank(不接受空白输入),集合判空用isEmpty

// ✅ defaultString: null安全取值
StringUtils.defaultString(str, "");         // null → ""
StringUtils.defaultIfBlank(str, "N/A");     // null/""/" " → "N/A"

// ✅ 填充与截断
StringUtils.leftPad("1", 3, '0');           // "001"
StringUtils.abbreviate("very long text", 10); // "very lo..."

Pattern 2: Commons IO file patterns

// ✅ 读取整个文件(小文件,<10MB)
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);

// ✅ 逐行读(大文件) — LineIterator 模式
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try { while (it.hasNext()) { String line = it.nextLine(); /* 处理 */ }
} finally { LineIterator.closeQuietly(it); }

// ✅ 流操作(需手动关流)
InputStream in = new URL("https://example.com").openStream();
try { String result = IOUtils.toString(in, StandardCharsets.UTF_8); }
finally { IOUtils.closeQuietly(in); }

// ❌ 反模式: IOUtils.toString() 读 1GB 文件 → 尝试创建1GB String → OOM

// ✅ 写入/复制/删除
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
FileUtils.copyFile(src, dest);
FileUtils.forceMkdir(dir);          // 递归创建目录
FileUtils.deleteDirectory(dir);      // 递归删除

// ✅ 文件名处理
FilenameUtils.getExtension("archive.tar.gz");  // "gz" (最后一个.)
FilenameUtils.getBaseName("/path/file.txt");   // "file"
String normalized = FilenameUtils.normalize("C:/a/../b/file.txt"); // "C:/b/file.txt"

Pattern 3: Commons Lang3 migration notes

// ❌ 旧包名 — 不要用
import org.apache.commons.lang.StringUtils;

// ✅ 新包名(3.0+) — 必须用
import org.apache.commons.lang3.StringUtils;

// Maven坐标
// groupId: commons-lang → org.apache.commons
// artifactId: commons-lang → commons-lang3

Pattern 4: Validate parameter validation

// ⚠️ Commons Lang 3.0 变化: Validate 校验 null 抛 NullPointerException
// (对齐JDK标准行为,以前抛 IllegalArgumentException)
Validate.notNull(obj, "参数不能为空: %s", name);   // 抛 NPE
Validate.isTrue(age > 0, "年龄必须>0");             // 抛 IllegalArgumentException
// 注意:验证null用Validate.notNull,验证状态用Validate.isTrue

Pattern 5: RandomStringUtils

// ✅ 随机字母数字(验证码/Token)
RandomStringUtils.randomAlphanumeric(6);      // "a3Bx9K"
RandomStringUtils.randomAlphanumeric(32);     // 32位Token
// ✅ 随机数字
RandomStringUtils.randomNumeric(6);           // "482931"
// ✅ 随机字母
RandomStringUtils.randomAlphabetic(8);        // "AbCdEfGh"

Pattern 6: Collection operations

// ⚠️ 包名: org.apache.commons.collections4 (不是 collections)
CollectionUtils.isEmpty(coll);
CollectionUtils.union(list1, list2);          // 并集
CollectionUtils.intersection(list1, list2);   // 交集
CollectionUtils.subtract(list1, list2);       // 差集(list1 - list2)

MapUtils.getString(map, "key", "default");    // null安全取值

Gotchas

  1. isEmpty vs isBlank — isEmpty(" ")→true (does not include spaces), isBlank(" ")→true (includes spaces)
  2. IOUtils.toString loads the entire stream into memory — for large files (>10MB) use LineIterator to read line by line
  3. IOUtils.toString does not close the stream — pair with finally { IOUtils.closeQuietly(in) }
  4. Lang3 DateUtils is incompatible with Java8 LocalDateTime — use the java.time API, use Commons only for legacy Date
  5. The Collections4 package name is collections4 — not collections (that is 3.x)
  6. Since Lang3 3.0, isAlpha/isNumeric/isAlphanumeric("")→false — earlier versions returned true
  7. Maven coordinates: groupId=org.apache.commons, artifactId=commons-lang3 — not commons-lang
  8. Validate.notNull throws NullPointerException — Validate.isTrue throws IllegalArgumentException

Data Privacy

This skill does not collect, store, or transmit any user data.