Apache Commons包详解
Apache Commons
是Apache软件基金会的项目。
Commons
的目的是提供可重用的、开源的Java代码。
Apache Commons包简介
Apache Commons提供了很多工具类库,他们几乎不依赖其他第三方的类库,接口稳定,集成简单,可以大大提高编码效率和代码质量。
Apache Commons组件库
请参考Apache Common官方网站:https://commons.apache.org/
Component | Description | Latest Version | Release Date |
---|---|---|---|
BCEL | Byte Code Engineering Library - analyze, create, and manipulate Java class files | 6.10.0 | 2022-12-06 |
BeanUtils | Easy-to-use wrappers around the Java reflection and introspection APIs. | v1.9.4 | 2019-08-13 |
BSF | Bean Scripting Framework - interface to scripting languages, including JSR-223 | v3.1 | 2010-06-24 |
Chain | Chain of Responsibility pattern implemention. | v1.2 | 2008-06-02 |
CLI | Command Line arguments parser. | v1.9.0 | 2021-10-27 |
Codec | General encoding/decoding algorithms (for example phonetic, base64, URL). | v1.17.1 | 2020-09-01 |
Collections | Extends or augments the Java Collections Framework. | v4.5.0-M2 | 2019-07-05 |
Compress | Defines an API for working with tar, zip and bzip2 files. | v1.27.1 | 2022-11-01 |
Configuration | Reading of configuration/preferences files in various formats. | v2.11.0 | 2022-07-03 |
Crypto | A cryptographic library optimized with AES-NI wrapping Openssl or JCE algorithm implementations. | v1.2.0 | 2023-01-23 |
CSV | Component for reading and writing comma separated value files. | v1.12.0 | 2023-02-02 |
Daemon | Alternative invocation mechanism for unix-daemon-like java code. | v1.4.0 | 2022-11-29 |
DBCP | Database connection pooling services. | v2.13.0 | 2021-08-04 |
DbUtils | JDBC helper library. | v1.8.1 | 2017-07-20 |
Digester | XML-to-Java-object mapping utility. | v3.2 | 2011-12-13 |
Library for sending e-mail from Java. | v1.6.0 | 2017-08-01 | |
Exec | API for dealing with external process execution and environment management in Java. | v1.4.0 | 2014-11-06 |
FileUpload | File upload capability for your servlets and web applications. | v1.5 | 2023-23-13 |
Functor | A functor is a function that can be manipulated as an object, or an object representing a single, generic function. | v1.0 | 2011 |
Geometry | Space and coordinates. | v1.0 | 2021-08-21 |
Imaging (previously called Sanselan) | A pure-Java image library. | v1.0.0-alpha5 | 2022-05-19 |
IO | Collection of I/O utilities. | v2.18.0 | 2021-07-13 |
JCI | Java Compiler Interface | v1.1 | 2013-10-14 |
JCS | Java Caching System | v2.2.1 | 2020-08-16 |
Jelly | XML based scripting and processing engine. | v1.0.1 | 2017-09-25 |
Jexl | Expression language which extends the Expression Language of the JSTL. | v3.4.0 | 2021-06-25 |
JXPath | Utilities for manipulating Java Beans using the XPath syntax. | v1.3 | 2008-08-14 |
Lang | Provides extra functionality for classes in java.lang. | v3.17.0 | 2021-02-26 |
Logging | Wrapper around a variety of logging API implementations. | v1.3.4 | 2014-07-11 |
Math | Lightweight, self-contained mathematics and statistics components. | v4.0-beta1 | 2022-12-20 |
Net | Collection of network utilities and protocol implementations. | v3.11.1 | 2022-12-02 |
Numbers | Number types (complex, quaternion, fraction) and utilities (arrays, combinatorics). | v1.2 | 2022-11-01 |
OGNL | An Object-Graph Navigation Language | v4.0 | 2013 |
Pool | Generic object pooling component. | v2.12.0 | 2021-08-18 |
Proxy | Library for creating dynamic proxies. | v1.0 | 2008-02-28 |
RDF | Common implementation of RDF 1.1 that could be implemented by systems on the JVM. | v0.5.0 | 2017-12-23 |
RNG | Implementations of random numbers generators. | v1.6 | 2022-10-10 |
SCXML | An implementation of the State Chart XML specification aimed at creating and maintaining a Java SCXML engine.It is capable of executing a state machine defined using a SCXML document, and abstracts out the environment interfaces. | v0.9 | 2008-12-01 |
Statistics | Statistics. | v1.1 | 2022-12-05 |
Text | Apache Commons Text is a library focused on algorithms working on strings. | v1.13.0 | 2022-09-28 |
Validator | Framework to define validators and validation rules in an xml file. | v1.9.0 | 2020-08-07 |
VFS | Virtual File System component for treating files, FTP, SMB, ZIP and such like as a single logical file system. | V2.9.0 | 2021-07-21 |
Weaver | Provides an easy way to enhance (weave) compiled bytecode. | V2.0 | 2018-09-07 |
Apache Commons常用组件
Commons BeanUtils
Jakarta Commons
项目提供了相当丰富的API,我们之前了解到的Commons Lang
只是众多API的比较核心的一小部分而已。Commons下面还有相当数量的子项目,用于解决各种各样不同方向的实际问题,BeanUtils
就是其中的一个,用于处理JavaBeans
。它利用Java的反射机制,从动态的生成对bean的getter和setter
的调用代码,到模拟创建一个动态的bean,等等。这个包看似简单,却是很多开源项目的基石:如在著名的Struts和Spring Framework中,我们都能找到BeanUtils
的影子。大家猜猜看,有哪位名人是BeanUtils
的作者之一?没错,就是Struts的创始人Craig McClanahan
。
Commons BeanUtils一共包括如下5个包:
org.apache.commons.beanutils – 核心包,定义一组Utils类和需要用到的接口规范
org.apache.commons.beanutils.converters – 转换String到需要类型的类,实现Converter接口
org.apache.commons.beanutils.locale –beanutils的locale敏感版本
org.apache.commons.beanutils.locale.converters– converters的locale敏感版本
org.apache.commons.collections – beanutils使用到的Collection类
说明:
针对Bean的一个工具集。由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装。
使用示例:
功能有很多,网站上有详细介绍。一个比较常用的功能是Bean Copy,也就是copy bean的属性。如果做分层架构开发的话就会用到,比如从PO(Persistent Object)拷贝数据到VO(Value Object)
。
传统方法如下:
//得到TeacherForm
TeacherForm teacherForm=(TeacherForm)form;
//构造Teacher对象
Teacher teacher=new Teacher();
//赋值
teacher.setName(teacherForm.getName());
teacher.setAge(teacherForm.getAge());
teacher.setGender(teacherForm.getGender());
teacher.setMajor(teacherForm.getMajor());
teacher.setDepartment(teacherForm.getDepartment());
//持久化Teacher对象到数据库
HibernateDAO= ;
HibernateDAO.save(teacher);
使用BeanUtils后,代码就大大改观了,如下所示:
//得到TeacherForm
TeacherForm teacherForm=(TeacherForm)form;
//构造Teacher对象
Teacher teacher=new Teacher();
//赋值
BeanUtils.copyProperties(teacher,teacherForm);
//持久化Teacher对象到数据库
HibernateDAO= ;
HibernateDAO.save(teacher);
Commons CLI
说明:
这是一个处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。
使用示例:
// create Options object
Options options = new Options();
// add t option, option is the command parameter, false indicates that
// this parameter is not required.
options.addOption("t", false, "display current time");
options.addOption("c", true, "country code");
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("t")) {
// print the date and time
}else {
// print the date
}
// get c option value
String countryCode = cmd.getOptionValue("c");
if(countryCode == null) {
// print default date
}else {
// print date for country specified by countryCode
}
Commons Codec
说明:
Codec包含一些通用的编码解码算法。包括一些语音编码器,Hex、Base64以及URL encoder。
Commons Collections
说明:
Commons Collections,又是一个重量级的东西,为Java标准的Collections API提供了相当好的补充。我不知道其他人,就我自己而言,让我用java.util.Collection
及其子类,加上java.util.Collections
类提供的操作方法,处理一些简单的数据结构问题还可以,稍微复杂一点的就觉得有点头痛,很多细节的地方需要我插入这样那样的小逻辑,或者感觉它太死板,不够灵活,再或者确实有点晦涩吧。再说了,如果我只是处理一般的数据结构问题,为什么不自己用数组或者自定义的链表来做,再加上Jakarta Commons
的Lang提供的ArrayUtils、StringUtils
等,已经基本够了,性能可以保证,那么还要这个Collections API干嘛。当然,说到这里有些偏激了,Collections当然有它存在的道理,能够把常用的数据结构归纳起来,以通用的方式去维护和访问,这应该说是一种进步,但是用起来似乎不够友好。这个时候我就会想,如果Java比现在做得更好用些,或者有一套第三方的API把我的这些需求抽象出来,实现了,该多好。Commons Collections
就是这样一套API。可以把这个工具看成是java.util
的扩展。
Commons Collections包结构共包含12个:
org.apache.commons.collections – CommonsCollections自定义的一组公用的接口和工具类
org.apache.commons.collections.bag – 实现Bag接口的一组类
org.apache.commons.collections.bidimap – 实现BidiMap系列接口的一组类
org.apache.commons.collections.buffer – 实现Buffer接口的一组类
org.apache.commons.collections.collection –实现java.util.Collection接口的一组类
org.apache.commons.collections.comparators– 实现java.util.Comparator接口的一组类
org.apache.commons.collections.functors –Commons Collections自定义的一组功能类
org.apache.commons.collections.iterators – 实现java.util.Iterator接口的一组类
org.apache.commons.collections.keyvalue – 实现集合和键/值映射相关的一组类
org.apache.commons.collections.list – 实现java.util.List接口的一组类
org.apache.commons.collections.map – 实现Map系列接口的一组类
org.apache.commons.collections.set – 实现Set系列接口的一组类
使用示例:举一个简单的例子
OrderedMap map = new LinkedMap();
map.put("FIVE", "5");
map.put("SIX", "6");
map.put("SEVEN", "7");
map.firstKey(); // returns "FIVE"
map.nextKey("FIVE"); // returns "SIX"
map.nextKey("SIX"); // returns "SEVEN"
Commons Configuration
说明:
Commons-Configuration
工具对各种各式的配置和参考文件提供读取帮助,这个工具是用来帮助处理配置文件的,支持很多种存储方式。
- Properties files
- XML documents
- Property list files (.plist)
- JNDI
- JDBC Datasource
- System properties
- Applet parameters
- Servlet parameters
使用示例:举一个Properties的简单例子
# usergui.properties, definining the GUI,
colors.background = #FFFFFF
colors.foreground = #000080
window.width = 500
window.height = 300
PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setProperty("colors.background", "#000000);
config.save();
config.save("usergui.backup.properties);//save a copy
Integer integer = config.getInteger("window.width");
Commons DBCP
说明:
Commons-DBCP 提供数据库连接池服务,Database Connection pool、Tomcat就是用的这个,不用我多说了吧,要用的自己去网站上看说明。
Commons DbUtils
说明: 我以前在写数据库程序的时候,往往把数据库操作单独做一个包。DbUtils
就是这样一个工具,以后开发不用再重复这样的工作了。值得一体的是,这个工具并不是现在流行的OR-Mapping
工具(比如Hibernate
),只是简化数据库操作,比如
QueryRunner run = new QueryRunner(dataSource);
// Execute the query and get the results back from the handler
Object[] result = (Object[]) run.query("SELECT * FROM Person WHERE name=?", "John Doe");
Commons FileUpload
说明:
FileUpload 使得在你可以在应用和Servlet中容易的加入强大和高性能的文件上传能力,比如jsp的上传文件功能。
使用示例:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
Commons HttpClient
说明:
Commons-HttpClient
提供了可以工作于HTTP协议客户端的一个框架,这个工具可以方便通过编程的方式去访问网站。
使用示例:
最简单的Get操作
GetMethod get = new GetMethod("http://jakarta.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
Commons IO
说明:
IO是一个I/O工具集,可以看成是java.io
的扩展,我觉得用起来非常方便。
使用示例:
- 读取Stream
标准代码:
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
InputStreamReader inR = new InputStreamReader( in );
BufferedReader buf = new BufferedReader( inR );
String line;
while ( ( line = buf.readLine() ) != null ) {
System.out.println( line );
}
} finally {
in.close();
}
使用IOUtils
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}
- 读取文件
File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");
- 察看剩余空间
long freeSpace = FileSystemUtils.freeSpace("C:/");
Commons JXPath
说明:
Commons-JXPath
提供了使用Xpath
语法操纵符合Java类命名规范的 JavaBeans
的工具。也支持 maps
, DOM
和其他对象模型。Xpath
你知道吧,那么JXpath
就是基于Java对象的Xpath
,也就是用Xpath
对Java对象进行查询。这个东西还是很有想像力的。
使用示例:
Address address = (Address)JXPathContext.newContext(vendor).
getValue("locations[address/zipCode='90210']/address");
上述代码等同于
Address address = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
Location location = (Location)it.next();
String zipCode = location.getAddress().getZipCode();
if (zipCode.equals("90210")){
address = location.getAddress();
break;
}
}
Commons Lang
说明:
Commons-Lang
提供了许多许多通用的工具类集,提供了一些java.lang中类的扩展功能。这个工具包可以看成是对java.lang
的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils
等工具类。
Commons Logging
说明:
Commons-Logging
是一个各种 logging API实现的包裹类
Commons Math
说明:
Math 是一个轻量的,自包含的数学和统计组件,解决了许多非常通用但没有及时出现在Java标准语言中的实践问题。这个包提供的功能有些和Commons Lang重复了,但是这个包更专注于做数学工具,功能更强大。
Commons Net
说明:
Net是一个网络工具集,基于NetComponents代码,包括FTP客户端等等,封装了很多网络协议。
- FTP
- NNTP
- SMTP
- POP3
- Telnet
- TFTP
- Finger
- Whois
- rexec/rcmd/rlogin
- Time (rdate) and Daytime
- Echo
- Discard
- NTP/SNTP
使用示例:
TelnetClient telnet = new TelnetClient();
telnet.connect( "192.168.1.99", 23 );
InputStream in = telnet.getInputStream();
PrintStream out = new PrintStream( telnet.getOutputStream() );
...
telnet.close();
Commons Primitives
Commons-Primitives
提供了一个更小,更快和更易使用的对Java基本类型的支持。当前主要是针对基本类型的 collection。
Commons Validator
说明:
The commons-validator
提供了一个简单的,可扩展的框架来在一个XML文件中定义校验器 (校验方法)和校验规则。支持校验规则的和错误消息的国际化。用来帮助进行验证的工具。比如验证Email字符串
,日期字符串
等是否合法。
使用示例:
// Get the Date validator
DateValidator validator = DateValidator.getInstance();
// Validate/Convert the date
Date fooDate = validator.validate(fooString, "dd/MM/yyyy");
if (fooDate == null) {
// error...not a valid date
return;
}
Commons Virtual File System
说明:
vfs
提供对各种资源的访问接口。支持的资源类型包括
- CIFS
- FTP
- Local Files
- HTTP and HTTPS
- SFTP
- Temporary Files
- WebDAV
- Zip, Jar and Tar (uncompressed, tgz or tbz2)
- gzip and bzip2
- res
- ram
这个包的功能很强大,极大的简化了程序对资源的访问。
使用示例:
从jar中读取文件
// Locate the Jar file
FileSystemManager fsManager = VFS.getManager();
FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
// List the children of the Jar file
FileObject[] children = jarFile.getChildren();
System.out.println( "Children of " + jarFile.getName().getURI() );
for ( int i = 0; i < children.length; i++ ){
System.out.println( children[ i ].getName().getBaseName() );
}
从smb读取文件
StaticUserAuthenticator auth = new StaticUserAuthenticator("username", "password", null);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile("smb://host/anyshare/dir", opts);