Apache Commons 系列框架详解:从基础工具到高级应用的全面探索
一、Apache Commons Lang
Apache Commons Lang 是一个用于扩展 Java 核心语言特性的工具库,提供了大量实用的工具类,用于操作字符串、数字、日期等。
(一)字符串操作
-
字符串工具类:
StringUtils提供了许多字符串操作方法,例如判断字符串是否为空、去除空白字符等。import org.apache.commons.lang3.StringUtils; public class StringUtilsExample { public static void main(String[] args) { String str = " Hello World "; System.out.println("Is blank: " + StringUtils.isBlank(str)); // 判断是否为空或空白 System.out.println("Trimmed: " + StringUtils.trim(str)); // 去除首尾空白 System.out.println("Upper case: " + StringUtils.upperCase(str)); // 转换为大写 } }输出结果:
Is blank: false Trimmed: Hello World Upper case: HELLO WORLD -
字符串替换:
StringUtils还支持复杂的字符串替换操作。String original = "Hello, ${name}!"; String replaced = StringUtils.replace(original, "${name}", "Kitty"); System.out.println(replaced); // 输出:Hello, Kitty!
(二)日期操作
- 日期工具类:
DateUtils提供了对日期的解析、格式化和计算功能。
输出结果:import org.apache.commons.lang3.time.DateUtils; import java.util.Date; public class DateUtilsExample { public static void main(String[] args) { Date now = new Date(); Date tomorrow = DateUtils.addDays(now, 1); // 添加一天 System.out.println("Tomorrow: " + tomorrow); Date parsedDate = DateUtils.parseDate("2025-04-10", "yyyy-MM-dd"); // 解析日期字符串 System.out.println("Parsed Date: " + parsedDate); } }Tomorrow: 2025-04-10 12:34:56 Parsed Date: 2025-04-10 00:00:00
(三)数字操作
- 数字工具类:
NumberUtils提供了对数字的转换和操作方法。
输出结果:import org.apache.commons.lang3.math.NumberUtils; public class NumberUtilsExample { public static void main(String[] args) { String numberStr = "123"; int number = NumberUtils.toInt(numberStr); // 将字符串转换为整数 System.out.println("Converted number: " + number); boolean isNumber = NumberUtils.isCreatable("abc"); // 判断是否可以转换为数字 System.out.println("Is number: " + isNumber); } }Converted number: 123 Is number: false
二、Apache Commons Collections
Apache Commons Collections 是一个增强版的 Java 集合框架,提供了许多扩展的集合类和工具类,用于更高效地操作集合。
(一)集合工具类
-
集合操作:
CollectionUtils提供了对集合的合并、筛选、查找等功能。import org.apache.commons.collections4.CollectionUtils; import java.util.ArrayList; import java.util.List; public class CollectionUtilsExample { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Apple"); list1.add("Banana"); List<String> list2 = new ArrayList<>(); list2.add("Banana"); list2.add("Orange"); List<String> intersection = new ArrayList<>(CollectionUtils.intersection(list1, list2)); // 求交集 System.out.println("Intersection: " + intersection); List<String> union = new ArrayList<>(CollectionUtils.union(list1, list2)); // 求并集 System.out.println("Union: " + union); } }输出结果:
Intersection: [Banana] Union: [Apple, Banana, Orange] -
集合转换:
ListUtils提供了对列表的分割、合并等功能。import org.apache.commons.collections4.ListUtils; import java.util.Arrays; import java.util.List; public class ListUtilsExample { public static void main(String[] args) { List<String> list1 = Arrays.asList("Apple", "Banana"); List<String> list2 = Arrays.asList("Orange", "Grapes"); List<String> combined = ListUtils.union(list1, list2); // 合并列表 System.out.println("Combined list: " + combined); List<List<String>> partitioned = ListUtils.partition(combined, 2); // 分割列表 System.out.println("Partitioned list: " + partitioned); } }输出结果:
Combined list: [Apple, Banana, Orange, Grapes] Partitioned list: [[Apple, Banana], [Orange, Grapes]]
(二)自定义集合类
- 双向队列:
BidiQueue是一个双向队列,支持从头部和尾部插入和删除元素。
输出结果:import org.apache.commons.collections4.bidimap.BidiMap; import org.apache.commons.collections4.bidimap.TreeBidiMap; public class BidiMapExample { public static void main(String[] args) { BidiMap<String, String> bidiMap = new TreeBidiMap<>(); bidiMap.put("Key1", "Value1"); bidiMap.put("Key2", "Value2"); System.out.println("Get by key: " + bidiMap.get("Key1")); // 通过键获取值 System.out.println("Get by value: " + bidiMap.getKey("Value2")); // 通过值获取键 } }Get by key: Value1 Get by value: Key2
三、Apache Commons IO
Apache Commons IO 是一个用于简化 Java IO 操作的工具库,提供了大量用于文件和流操作的实用方法。
(一)文件操作
-
文件工具类:
FileUtils提供了对文件的复制、删除、移动等功能。import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class FileUtilsExample { public static void main(String[] args) { File sourceFile = new File("source.txt"); File targetFile = new File("target.txt"); try { FileUtils.copyFile(sourceFile, targetFile); // 复制文件 System.out.println("File copied successfully."); FileUtils.deleteQuietly(sourceFile); // 安静删除文件 System.out.println("Source file deleted."); } catch (IOException e) { e.printStackTrace(); } } } -
文件内容操作:
FileUtils还支持读取和写入文件内容。import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class FileUtilsContentExample { public static void main(String[] args) { File file = new File("example.txt"); try { String content = FileUtils.readFileToString(file, "UTF-8"); // 读取文件内容 System.out.println("File content: " + content); FileUtils.writeStringToFile(file, "Hello, world!", "UTF-8"); // 写入文件内容 System.out.println("File written successfully."); } catch (IOException e) { e.printStackTrace(); } } }
(二)流操作
- 流工具类:
IOUtils提供了对输入流和输出流的复制、关闭等功能。import org.apache.commons.io.IOUtils; import java.io.*; public class IOUtilsExample { public static void main(String[] args) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new FileInputStream("source.txt"); outputStream = new FileOutputStream("target.txt"); IOUtils.copy(inputStream, outputStream); // 复制流 System.out.println("Stream copied successfully."); IOUtils.closeQuietly(inputStream); // 安静关闭流 IOUtils.closeQuietly(outputStream); } catch (IOException e) { e.printStackTrace(); } } }
四、Apache Commons BeanUtils
Apache Commons BeanUtils 是一个用于操作 JavaBean 的工具库,提供了对 JavaBean 的属性访问、复制等功能。
(一)JavaBean 操作
-
属性访问:
BeanUtils提供了对 JavaBean 属性的动态访问和设置。import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; public class BeanUtilsExample { public static void main(String[] args) { Person person = new Person(); try { BeanUtils.setProperty(person, "name", "Kitty"); // 设置属性 BeanUtils.setProperty(person, "age", "25"); System.out.println("Name: " + BeanUtils.getProperty(person, "name")); // 获取属性 System.out.println("Age: " + BeanUtils.getProperty(person, "age")); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } } } class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }输出结果:
Name: Kitty Age: 25 -
对象复制:
BeanUtils支持将一个对象的属性复制到另一个对象。import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; public class BeanUtilsCopyExample { public static void main(String[] args) { Person source = new Person("Kitty", 25); Person target = new Person(); try { BeanUtils.copyProperties(target, source); // 复制属性 System.out.println("Target name: " + target.getName()); System.out.println("Target age: " + target.getAge()); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }输出结果:
Target name: Kitty Target age: 25
五、Apache Commons Codec
Apache Commons Codec 是一个用于实现常用编码和解码算法的工具库,支持 Base64、Hex、URL 编码等。
(一)Base64 编码
- Base64 编码和解码:
Base64类提供了对字符串的 Base64 编码和解码功能。
输出结果:import org.apache.commons.codec.binary.Base64; public class Base64Example { public static void main(String[] args) { String originalString = "Hello, world!"; byte[] encodedBytes = Base64.encodeBase64(originalString.getBytes()); // 编码 String encodedString = new String(encodedBytes); System.out.println("Encoded string: " + encodedString); byte[] decodedBytes = Base64.decodeBase64(encodedBytes); // 解码 String decodedString = new String(decodedBytes); System.out.println("Decoded string: " + decodedString); } }Encoded string: SGVsbG8sIHdvcmxkIQ== Decoded string: Hello, world!
(二)Hex 编码
- Hex 编码和解码:
Hex类提供了对字节数组的十六进制编码和解码功能。
输出结果:import org.apache.commons.codec.binary.Hex; public class HexExample { public static void main(String[] args) { byte[] originalBytes = "Hello".getBytes(); String hexString = Hex.encodeHexString(originalBytes); // 编码 System.out.println("Hex string: " + hexString); byte[] decodedBytes = Hex.decodeHex(hexString.toCharArray()); // 解码 String decodedString = new String(decodedBytes); System.out.println("Decoded string: " + decodedString); } }Hex string: 48656c6c6f Decoded string: Hello
(三)URL 编码
- URL 编码和解码:
UrlCodec类提供了对字符串的 URL 编码和解码功能。
输出结果:import org.apache.commons.codec.net.UrlCodec; public class UrlCodecExample { public static void main(String[] args) { String originalString = "Hello world!"; UrlCodec codec = new UrlCodec(); String encodedString = codec.encode(originalString); // 编码 System.out.println("Encoded string: " + encodedString); String decodedString = codec.decode(encodedString); // 解码 System.out.println("Decoded string: " + decodedString); } }Encoded string: Hello+world%21 Decoded string: Hello world!
六、Apache Commons Net
Apache Commons Net 是一个用于实现网络协议的工具库,支持 FTP、SMTP、POP3 等常见网络协议。
(一)FTP 客户端
- FTP 文件上传和下载:
FTPClient类提供了对 FTP 服务器的连接、文件上传和下载功能。import org.apache.commons.net.ftp.FTPClient; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FTPClientExample { public static void main(String[] args) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect("ftp.example.com"); // 连接到 FTP 服务器 ftpClient.login("username", "password"); // 上传文件 FileInputStream inputStream = new FileInputStream("localFile.txt"); ftpClient.storeFile("remoteFile.txt", inputStream); inputStream.close(); // 下载文件 FileOutputStream outputStream = new FileOutputStream("downloadedFile.txt"); ftpClient.retrieveFile("remoteFile.txt", outputStream); outputStream.close(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
(二)SMTP 客户端
- 发送邮件:
SMTPClient类提供了对 SMTP 协议的支持,用于发送邮件。import org.apache.commons.net.smtp.SMTPClient; import java.io.IOException; public class SMTPClientExample { public static void main(String[] args) { SMTPClient smtpClient = new SMTPClient(); try { smtpClient.connect("smtp.example.com"); // 连接到 SMTP 服务器 smtpClient.login("username", "password"); smtpClient.sendCommand("MAIL FROM:<sender@example.com>"); // 发送邮件命令 smtpClient.sendCommand("RCPT TO:<recipient@example.com>"); smtpClient.sendCommand("DATA"); smtpClient.sendCommand("From: sender@example.com"); smtpClient.sendCommand("To: recipient@example.com"); smtpClient.sendCommand("Subject: Test Email"); smtpClient.sendCommand("Hello, this is a test email."); smtpClient.sendCommand("."); smtpClient.logout(); smtpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
七、Apache Commons Math
Apache Commons Math 是一个用于数学计算的工具库,提供了线性代数、概率统计、数值分析等功能。
(一)概率统计
-
概率分布:
NormalDistribution类提供了正态分布的概率计算功能。import org.apache.commons.math3.distribution.NormalDistribution; public class NormalDistributionExample { public static void main(String[] args) { NormalDistribution normalDistribution = new NormalDistribution(0, 1); // 创建正态分布对象 double probability = normalDistribution.cumulativeProbability(1.96); // 计算累积概率 System.out.println("Probability: " + probability); } }输出结果:
Probability: 0.9750021048517795 -
统计量计算:
DescriptiveStatistics类提供了对数据集的描述性统计功能。import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DescriptiveStatisticsExample { public static void main(String[] args) { DescriptiveStatistics stats = new DescriptiveStatistics(); stats.addValue(1.0); stats.addValue(2.0); stats.addValue(3.0); System.out.println("Mean: " + stats.getMean()); // 计算平均值 System.out.println("Standard Deviation: " + stats.getStandardDeviation()); // 计算标准差 } }输出结果:
Mean: 2.0 Standard Deviation: 0.8164965809277259
(二)线性代数
- 矩阵操作:
RealMatrix类提供了矩阵的创建、加法、乘法等功能。
输出结果:import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; public class RealMatrixExample { public static void main(String[] args) { double[][] data1 = {{1, 2}, {3, 4}}; double[][] data2 = {{5, 6}, {7, 8}}; RealMatrix matrix1 = new Array2DRowRealMatrix(data1); // 创建矩阵 RealMatrix matrix2 = new Array2DRowRealMatrix(data2); RealMatrix sum = matrix1.add(matrix2); // 矩阵加法 System.out.println("Sum matrix:"); System.out.println(sum.getRow(0)[0] + " " + sum.getRow(0)[1]); System.out.println(sum.getRow(1)[0] + " " + sum.getRow(1)[1]); RealMatrix product = matrix1.multiply(matrix2); // 矩阵乘法 System.out.println("Product matrix:"); System.out.println(product.getRow(0)[0] + " " + product.getRow(0)[1]); System.out.println(product.getRow(1)[0] + " " + product.getRow(1)[1]); } }Sum matrix: 6.0 8.0 10.0 12.0 Product matrix: 19.0 22.0 43.0 50.0
八、Apache Commons Validator
Apache Commons Validator 是一个用于数据验证的工具库,支持对字符串、数字等数据类型的格式验证。
(一)数据验证
-
字符串验证:
Validator类提供了对字符串的长度、格式等验证功能。import org.apache.commons.validator.routines.EmailValidator; public class ValidatorExample { public static void main(String[] args) { String email = "example@example.com"; boolean isValid = EmailValidator.getInstance().isValid(email); // 验证电子邮件格式 System.out.println("Is valid email: " + isValid); } }输出结果:
Is valid email: true -
数字验证:
NumberValidator类提供了对数字的范围、精度等验证功能。import org.apache.commons.validator.routines.IntegerValidator; public class IntegerValidatorExample { public static void main(String[] args) { String numberStr = "123"; IntegerValidator validator = IntegerValidator.getInstance(); boolean isValid = validator.isValid(numberStr); // 验证是否为有效整数 System.out.println("Is valid integer: " + isValid); } }输出结果:
Is valid integer: true
九、Apache Commons Configuration
Apache Commons Configuration 是一个用于读取和管理配置文件的工具库,支持多种配置文件格式(如 XML、Properties 等)。
(一)配置文件读取
-
Properties 配置文件:
PropertiesConfiguration类提供了对 Properties 文件的读取和写入功能。import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; public class PropertiesConfigurationExample { public static void main(String[] args) { Configurations configs = new Configurations(); try { PropertiesConfiguration config = configs.properties("config.properties"); // 加载配置文件 String name = config.getString("name"); // 获取配置项 int age = config.getInt("age"); System.out.println("Name: " + name); System.out.println("Age: " + age); } catch (ConfigurationException e) { e.printStackTrace(); } } }假设
config.properties文件内容如下:name=Kitty age=25输出结果:
Name: Kitty Age: 25 -
XML 配置文件:
XMLConfiguration类提供了对 XML 文件的读取和写入功能。import org.apache.commons.configuration2.XMLConfiguration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; public class XMLConfigurationExample { public static void main(String[] args) { Configurations configs = new Configurations(); try { XMLConfiguration config = configs.xml("config.xml"); // 加载配置文件 String name = config.getString("name"); // 获取配置项 int age = config.getInt("age"); System.out.println("Name: " + name); System.out.println("Age: " + age); } catch (ConfigurationException e) { e.printStackTrace(); } } }假设
config.xml文件内容如下:<config> <name>Kitty</name> <age>25</age> </config>输出结果:
Name: Kitty Age: 25
十、Apache Commons Pool
Apache Commons Pool 是一个用于管理对象池的工具库,支持创建和管理对象池,提高对象复用效率。
(一)对象池
- 创建对象池:
GenericObjectPool类提供了对对象池的创建和管理功能。
输出结果:import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; public class GenericObjectPoolExample { public static void main(String[] args) { GenericObjectPoolConfig<String> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(10); // 设置最大对象数量 config.setMaxIdle(5); // 设置最大空闲对象数量 config.setMinIdle(2); // 设置最小空闲对象数量 GenericObjectPool<String> pool = new GenericObjectPool<>(new StringFactory(), config); // 创建对象池 try { String borrowedObject = pool.borrowObject(); // 借用对象 System.out.println("Borrowed object: " + borrowedObject); pool.returnObject(borrowedObject); // 归还对象 } catch (Exception e) { e.printStackTrace(); } } static class StringFactory implements org.apache.commons.pool2.PooledObjectFactory<String> { @Override public org.apache.commons.pool2.PooledObject<String> makeObject() throws Exception { return new org.apache.commons.pool2.impl.DefaultPooledObject<>(new String("Hello")); } @Override public void destroyObject(org.apache.commons.pool2.PooledObject<String> p) throws Exception { } @Override public boolean validateObject(org.apache.commons.pool2.PooledObject<String> p) { return true; } @Override public void activateObject(org.apache.commons.pool2.PooledObject<String> p) throws Exception { } @Override public void passivateObject(org.apache.commons.pool2.PooledObject<String> p) throws Exception { } } }Borrowed object: Hello
浙公网安备 33010602011771号