Apache Commons包详解


Apache Commons 是Apache软件基金会的项目。 Commons 的目的是提供可重用的、开源的Java代码。

Apache Commons包简介

Apache Commons提供了很多工具类库,他们几乎不依赖其他第三方的类库,接口稳定,集成简单,可以大大提高编码效率和代码质量。

Apache Commons组件库

请参考Apache Common官方网站:https://commons.apache.org/

ComponentDescriptionLatest VersionRelease Date
BCELByte Code Engineering Library - analyze, create, and manipulate Java class files6.10.02022-12-06
BeanUtilsEasy-to-use wrappers around the Java reflection and introspection APIs.v1.9.42019-08-13
BSFBean Scripting Framework - interface to scripting languages, including JSR-223v3.12010-06-24
ChainChain of Responsibility pattern implemention.v1.22008-06-02
CLICommand Line arguments parser.v1.9.02021-10-27
CodecGeneral encoding/decoding algorithms (for example phonetic, base64, URL).v1.17.12020-09-01
CollectionsExtends or augments the Java Collections Framework.v4.5.0-M22019-07-05
CompressDefines an API for working with tar, zip and bzip2 files.v1.27.12022-11-01
ConfigurationReading of configuration/preferences files in various formats.v2.11.02022-07-03
CryptoA cryptographic library optimized with AES-NI wrapping Openssl or JCE algorithm implementations.v1.2.02023-01-23
CSVComponent for reading and writing comma separated value files.v1.12.02023-02-02
DaemonAlternative invocation mechanism for unix-daemon-like java code.v1.4.02022-11-29
DBCPDatabase connection pooling services.v2.13.02021-08-04
DbUtilsJDBC helper library.v1.8.12017-07-20
DigesterXML-to-Java-object mapping utility.v3.22011-12-13
EmailLibrary for sending e-mail from Java.v1.6.02017-08-01
ExecAPI for dealing with external process execution and environment management in Java.v1.4.02014-11-06
FileUploadFile upload capability for your servlets and web applications.v1.52023-23-13
FunctorA functor is a function that can be manipulated as an object, or an object representing a single, generic function.v1.02011
GeometrySpace and coordinates.v1.02021-08-21
Imaging (previously called Sanselan)A pure-Java image library.v1.0.0-alpha52022-05-19
IOCollection of I/O utilities.v2.18.02021-07-13
JCIJava Compiler Interfacev1.12013-10-14
JCSJava Caching Systemv2.2.12020-08-16
JellyXML based scripting and processing engine.v1.0.12017-09-25
JexlExpression language which extends the Expression Language of the JSTL.v3.4.02021-06-25
JXPathUtilities for manipulating Java Beans using the XPath syntax.v1.32008-08-14
LangProvides extra functionality for classes in java.lang.v3.17.02021-02-26
LoggingWrapper around a variety of logging API implementations.v1.3.42014-07-11
MathLightweight, self-contained mathematics and statistics components.v4.0-beta12022-12-20
NetCollection of network utilities and protocol implementations.v3.11.12022-12-02
NumbersNumber types (complex, quaternion, fraction) and utilities (arrays, combinatorics).v1.22022-11-01
OGNLAn Object-Graph Navigation Languagev4.02013
PoolGeneric object pooling component.v2.12.02021-08-18
ProxyLibrary for creating dynamic proxies.v1.02008-02-28
RDFCommon implementation of RDF 1.1 that could be implemented by systems on the JVM.v0.5.02017-12-23
RNGImplementations of random numbers generators.v1.62022-10-10
SCXMLAn 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.92008-12-01
StatisticsStatistics.v1.12022-12-05
TextApache Commons Text is a library focused on algorithms working on strings.v1.13.02022-09-28
ValidatorFramework to define validators and validation rules in an xml file.v1.9.02020-08-07
VFSVirtual File System component for treating files, FTP, SMB, ZIP and such like as a single logical file system.V2.9.02021-07-21
WeaverProvides an easy way to enhance (weave) compiled bytecode.V2.02018-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的扩展,我觉得用起来非常方便。

使用示例:

  1. 读取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);
}
  1. 读取文件
File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");
  1. 察看剩余空间
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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一名技术极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值