Apache Commons
2014-06-19 18:02 【戈多】 阅读(450) 评论(1) 编辑 收藏 举报Apache Commons 是一个非常有用的工具包,解决各种实际的通用问题,你会发现它们正是你冥思苦想所需要的东西。它们不是绝世武功,但确是个随手可用的擒手,Commons一出,问题手到擒来。常用的有:
commons-lang
commons-collections
commons-io
commons-beanutils
,下面是一个全面的简述表:
组件 |
说明 |
BeanUtils | Commons-BeanUtils 提供对 Java 反射和自省API的包装 |
Betwixt | Betwixt提供将 JavaBean 映射至 XML 文档,以及相反映射的服务. |
Chain |
Chain 提供实现组织复杂的处理流程的“责任链模式”. |
CLI |
CLI 提供针对命令行参数,选项,选项组,强制选项等的简单API. |
Codec |
Codec 包含一些通用的编码解码算法。包括一些语音编码器, Hex, Base64, 以及URL encoder. |
Collections |
Commons-Collections 提供一个类包来扩展和增加标准的 Java Collection框架 |
Configuration |
Commons-Configuration 工具对各种各式的配置和参考文件提供读取帮助. |
Daemon |
一种 unix-daemon-like java 代码的替代机制 |
DBCP |
Commons-DBCP 提供数据库连接池服务 |
DbUtils |
DbUtils 是一个 JDBC helper 类库,完成数据库任务的简单的资源清除代码. |
Digester |
Commons-Digester 是一个 XML-Java对象的映射工具,用于解析 XML配置文件. |
Discovery |
Commons-Discovery 提供工具来定位资源 (包括类) ,通过使用各种模式来映射服务/引用名称和资源名称. |
EL |
Commons-EL 提供在JSP2.0规范中定义的EL表达式的解释器. |
FileUpload |
FileUpload 使得在你可以在应用和Servlet中容易的加入强大和高性能的文件上传能力. |
HttpClient |
Commons-HttpClient 提供了可以工作于HTTP协议客户端的一个框架. |
IO |
IO 是一个 I/O 工具集. |
Jelly |
Jelly是一个基于 XML 的脚本和处理引擎。 Jelly 借鉴了 JSP 定指标签,Velocity, Cocoon和Xdoclet中的脚本引擎的许多优点。Jelly 可以用在命令行, Ant 或者 Servlet之中. |
Jexl |
Jexl是一个表达式语言,通过借鉴来自于Velocity的经验扩展了JSTL定义的表达式语言. |
JXPath |
Commons-JXPath 提供了使用Xpath语法操纵符合Java类命名规范的 JavaBeans的工具。也支持 maps, DOM 和其他对象模型. |
Lang |
Commons-Lang 提供了许多许多通用的工具类集,提供了一些java.lang中类的扩展功能. |
Latka |
Commons-Latka 是一个HTTP 功能测试包,用于自动化的QA,验收和衰减测试. |
Launcher |
Launcher 组件是一个交叉平台的Java 应用载入器。 Commons-launcher 消除了需要批处理或者Shell脚本来载入Java 类。.原始的 Java 类来自于Jakarta Tomcat 4.0 项目. |
Logging |
Commons-Logging 是一个各种 logging API实现的包裹类. |
Math |
Math 是一个轻量的,自包含的数学和统计组件,解决了许多非常通用但没有及时出现在Java标准语言中的实践问题. |
Modeler |
Commons-Modeler 提供了建模兼容JMX规范的 Mbean的机制. |
Net |
Net 是一个网络工具集,基于 NetComponents 代码,包括 FTP 客户端等等. |
Pool |
Commons-Pool 提供了通用对象池接口,一个用于创建模块化对象池的工具包,以及通常的对象池实现. |
Primitives |
Commons-Primitives提供了一个更小,更快和更易使用的对Java基本类型的支持。当前主要是针对基本类型的 collection. |
Validator |
The commons-validator提供了一个简单的,可扩展的框架来在一个XML文件中定义校验器 (校验方法)和校验规则。支持校验规则的和错误消息的国际化. |
详细信息位于:http://jakarta.apache.org/commons/index.html
一、commons.lang包方法集锦
import java.util.Iterator; import java.util.Map; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; /** * commons-lang-2.4.jar 包常用方法集锦 * */ public class CommonsLang { public static void main(String[] args) { String[] test = { "33", "ddffd" }; String[] test1 = { "ddffd", "33" }; // 1.判断两个数据是否相等 System.out.println(ArrayUtils.isEquals(test, test1)); // 2.{33,ddffd} 将数组内容以{,}形式输出. System.out.println(ArrayUtils.toString(test)); Map map = ArrayUtils.toMap(new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }); // 3.toMap 一个数组,但每个元素 Each element of the array // must be either a {@link java.util.Map.Entry} or an Array, // 方式一 下面是遍历map的方式,取得其keySet.iterator(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); // it.next()只包含key System.out.println("key:" + key + "value:" + map.get(key)); } // 方式二,取得其entrySet()集合, Iterator it1 = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it1.next(); // it1.next()中包含key和value System.out.println("key :" + entry.getKey() + "value :" + entry.getValue()); } // 4.取得类名 System.out.println(ClassUtils.getShortClassName(CommonsLang.class)); // 取得其包名 System.out.println(ClassUtils.getPackageName(CommonsLang.class)); // 5.NumberUtils System.out.println(NumberUtils.stringToInt("6")); System.out.println(NumberUtils.stringToInt("7", 10)); // 6.五位的随机字母和数字 System.out.println(RandomStringUtils.randomAlphanumeric(5)); // 7.StringEscapeUtils System.out.println(StringEscapeUtils.escapeHtml("<html>")); // 输出结果为<html> System.out.println(StringEscapeUtils.escapeJava("String")); // 8.StringUtils,判断是否是空格字符 System.out.println(StringUtils.isBlank(" ")); // 将数组中的内容以,分隔 System.out.println(StringUtils.join(test, ",")); // 在右边加下字符,使之总长度为6 System.out.println(StringUtils.rightPad("abc", 6, 'T')); // 首字母大写 System.out.println(StringUtils.capitalize("abc")); // Deletes all whitespaces from a String 删除所有空格 System.out.println(StringUtils.deleteWhitespace(" ab c ")); // 判断是否包含这个字符 System.out.println(StringUtils.contains("abc", "ba")); // 表示左边两个字符 System.out.println(StringUtils.left("abc", 2)); System.out.println(StringUtils.right("abcd", 3)); } }
二、commons.lang包方法集锦
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.CharSet; import org.apache.commons.lang.CharSetUtils; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.SerializationUtils; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.lang.time.StopWatch; public class LangDemo { public void charSetDemo() { System.out.println("**CharSetDemo**"); CharSet charSet = CharSet.getInstance("aeiou"); String demoStr = "The quick brown fox jumps over the lazy dog."; int count = 0; for (int i = 0, len = demoStr.length(); i < len; i++) { if (charSet.contains(demoStr.charAt(i))) { count++; } } System.out.println("count: " + count); } public void charSetUtilsDemo() { System.out.println("**CharSetUtilsDemo**"); System.out.println("计算字符串中包含某字符数."); System.out.println(CharSetUtils.count( "The quick brown fox jumps over the lazy dog.", "aeiou")); System.out.println("删除字符串中某字符."); System.out.println(CharSetUtils.delete( "The quick brown fox jumps over the lazy dog.", "aeiou")); System.out.println("保留字符串中某字符."); System.out.println(CharSetUtils.keep( "The quick brown fox jumps over the lazy dog.", "aeiou")); System.out.println("合并重复的字符."); System.out.println(CharSetUtils.squeeze("a bbbbbb c dd", "b d")); } public void objectUtilsDemo() { System.out.println("**ObjectUtilsDemo**"); System.out.println("Object为null时,默认打印某字符."); Object obj = null; System.out.println(ObjectUtils.defaultIfNull(obj, "空")); System.out.println("验证两个引用是否指向的Object是否相等,取决于Object的equals()方法."); Object a = new Object(); Object b = a; Object c = new Object(); System.out.println(ObjectUtils.equals(a, b)); System.out.println(ObjectUtils.equals(a, c)); System.out.println("用父类Object的toString()方法返回对象信息."); Date date = new Date(); System.out.println(ObjectUtils.identityToString(date)); System.out.println(date); System.out.println("返回类本身的toString()方法结果,对象为null时,返回0长度字符串."); System.out.println(ObjectUtils.toString(date)); System.out.println(ObjectUtils.toString(null)); System.out.println(date); } public void serializationUtilsDemo() { System.out.println("*SerializationUtils**"); Date date = new Date(); byte[] bytes = SerializationUtils.serialize(date); System.out.println(ArrayUtils.toString(bytes)); System.out.println(date); Date reDate = (Date) SerializationUtils.deserialize(bytes); System.out.println(reDate); System.out.println(ObjectUtils.equals(date, reDate)); System.out.println(date == reDate); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(new File("d:/test.txt")); fis = new FileInputStream(new File("d:/test.txt")); SerializationUtils.serialize(date, fos); Date reDate2 = (Date) SerializationUtils.deserialize(fis); System.out.println(date.equals(reDate2)); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { fos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } public void randomStringUtilsDemo() { System.out.println("**RandomStringUtilsDemo**"); System.out.println("生成指定长度的随机字符串,好像没什么用."); System.out.println(RandomStringUtils.random(500)); System.out.println("在指定字符串中生成长度为n的随机字符串."); System.out.println(RandomStringUtils.random(5, "abcdefghijk")); System.out.println("指定从字符或数字中生成随机字符串."); System.out.println(RandomStringUtils.random(5, true, false)); System.out.println(RandomStringUtils.random(5, false, true)); } public void stringUtilsDemo() { System.out.println("**StringUtilsDemo**"); System.out.println("将字符串重复n次,将文字按某宽度居中,将字符串数组用某字符串连接."); String[] header = new String[3]; header[0] = StringUtils.repeat("*", 50); header[1] = StringUtils.center(" StringUtilsDemo ", 50, "^O^"); header[2] = header[0]; String head = StringUtils.join(header, "/n"); System.out.println(head); System.out.println("缩短到某长度,用...结尾."); System.out.println(StringUtils.abbreviate( "The quick brown fox jumps over the lazy dog.", 10)); System.out.println(StringUtils.abbreviate( "The quick brown fox jumps over the lazy dog.", 15, 10)); System.out.println("返回两字符串不同处索引号."); System.out.println(StringUtils.indexOfDifference("aaabc", "aaacc")); System.out.println("返回两字符串不同处开始至结束."); System.out.println(StringUtils.difference("aaabcde", "aaaccde")); System.out.println("截去字符串为以指定字符串结尾的部分."); System.out.println(StringUtils.chomp("aaabcde", "de")); System.out.println("检查一字符串是否为另一字符串的子集."); System.out.println(StringUtils.containsOnly("aad", "aadd")); System.out.println("检查一字符串是否不是另一字符串的子集."); System.out.println(StringUtils.containsNone("defg", "aadd")); System.out.println("检查一字符串是否包含另一字符串."); System.out.println(StringUtils.contains("defg", "ef")); System.out.println(StringUtils.containsOnly("ef", "defg")); System.out.println("返回可以处理null的toString()."); System.out.println(StringUtils.defaultString("aaaa")); System.out.println("?" + StringUtils.defaultString(null) + "!"); System.out.println("去除字符中的空格."); System.out.println(StringUtils.deleteWhitespace("aa bb cc")); System.out.println("判断是否是某类字符."); System.out.println(StringUtils.isAlpha("ab")); System.out.println(StringUtils.isAlphanumeric("12")); System.out.println(StringUtils.isBlank("")); System.out.println(StringUtils.isNumeric("123")); } public void systemUtilsDemo() { System.out.println(genHeader("SystemUtilsDemo")); System.out.println("获得系统文件分隔符."); System.out.println(SystemUtils.FILE_SEPARATOR); System.out.println("获得源文件编码."); System.out.println(SystemUtils.FILE_ENCODING); System.out.println("获得ext目录."); System.out.println(SystemUtils.JAVA_EXT_DIRS); System.out.println("获得java版本."); System.out.println(SystemUtils.JAVA_VM_VERSION); System.out.println("获得java厂商."); System.out.println(SystemUtils.JAVA_VENDOR); } public void classUtilsDemo() { System.out.println(genHeader("ClassUtilsDemo")); System.out.println("获取类实现的所有接口."); System.out.println(ClassUtils.getAllInterfaces(Date.class)); System.out.println("获取类所有父类."); System.out.println(ClassUtils.getAllSuperclasses(Date.class)); System.out.println("获取简单类名."); System.out.println(ClassUtils.getShortClassName(Date.class)); System.out.println("获取包名."); System.out.println(ClassUtils.getPackageName(Date.class)); System.out.println("判断是否可以转型."); System.out.println(ClassUtils.isAssignable(Date.class, Object.class)); System.out.println(ClassUtils.isAssignable(Object.class, Date.class)); } public void stringEscapeUtilsDemo() { System.out.println(genHeader("StringEcsapeUtils")); System.out.println("转换特殊字符."); System.out.println("html:" + StringEscapeUtils.escapeHtml("")); System.out.println("html:" + StringEscapeUtils.unescapeHtml("<p>")); } private final class BuildDemo { String name; int age; public BuildDemo(String name, int age) { this.name = name; this.age = age; } public String toString() { ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE); tsb.append("Name", name); tsb.append("Age", age); return tsb.toString(); } public int hashCode() { HashCodeBuilder hcb = new HashCodeBuilder(); hcb.append(name); hcb.append(age); return hcb.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof BuildDemo)) { return false; } BuildDemo bd = (BuildDemo) obj; EqualsBuilder eb = new EqualsBuilder(); eb.append(name, bd.name); eb.append(age, bd.age); return eb.isEquals(); } } public void builderDemo() { System.out.println(genHeader("BuilderDemo")); BuildDemo obj1 = new BuildDemo("a", 1); BuildDemo obj2 = new BuildDemo("b", 2); BuildDemo obj3 = new BuildDemo("a", 1); System.out.println("toString()"); System.out.println(obj1); System.out.println(obj2); System.out.println(obj3); System.out.println("hashCode()"); System.out.println(obj1.hashCode()); System.out.println(obj2.hashCode()); System.out.println(obj3.hashCode()); System.out.println("equals()"); System.out.println(obj1.equals(obj2)); System.out.println(obj1.equals(obj3)); } public void numberUtils() { System.out.println(genHeader("NumberUtils")); System.out.println("字符串转为数字(不知道有什么用)."); System.out.println(NumberUtils.stringToInt("ba", 33)); System.out.println("从数组中选出最大值."); System.out.println(NumberUtils.max(new int[] { 1, 2, 3, 4 })); System.out.println("判断字符串是否全是整数."); System.out.println(NumberUtils.isDigits("123.1")); System.out.println("判断字符串是否是有效数字."); System.out.println(NumberUtils.isNumber("0123.1")); } public void dateFormatUtilsDemo() { System.out.println(genHeader("DateFormatUtilsDemo")); System.out.println("格式化日期输出."); System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss")); System.out.println("秒表."); StopWatch sw = new StopWatch(); sw.start(); for (Iterator iterator = DateUtils.iterator(new Date(), DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();) { Calendar cal = (Calendar) iterator.next(); System.out.println(DateFormatUtils.format(cal.getTime(), "yy-MM-dd HH:mm")); } sw.stop(); System.out.println("秒表计时:" + sw.getTime()); } private String genHeader(String head) { String[] header = new String[3]; header[0] = StringUtils.repeat("*", 50); header[1] = StringUtils.center(" " + head + " ", 50, "^O^"); header[2] = header[0]; return StringUtils.join(header, "/n"); } /** * @param args */ public static void main(String[] args) { LangDemo langDemo = new LangDemo(); langDemo.charSetDemo(); langDemo.charSetUtilsDemo(); langDemo.objectUtilsDemo(); langDemo.serializationUtilsDemo(); langDemo.randomStringUtilsDemo(); langDemo.stringUtilsDemo(); langDemo.systemUtilsDemo(); langDemo.classUtilsDemo(); langDemo.stringEscapeUtilsDemo(); langDemo.builderDemo(); langDemo.numberUtils(); langDemo.dateFormatUtilsDemo(); } }
三、commons.lang包(StringUtils)方法集锦
处理文本对 Java 应用来说应该算是家常便饭了,在 1.4 出现之前, Java 自身提供的 API 非常有限,如 String 、StringTokenizer 、 StringBuffer ,操作也比较单一。无非就是查找 substring 、分解、合并等等。到 1.4 的出现可以说 Java 的文字处理上了一个台阶,因为它支持 regular expression 了。这可是个重量级而方便的东东啊,缺点是太复杂,学习起来有一定难度。相较而言, Jakarta Commons 提供的 StringUtils 和 WordUtils 至今还维持着那种简洁而强大的美,使用起来也很顺手。来看一个例子:
package sean.study.jakarta.commons.lang; import org.apache.commons.lang.StringUtils; public class StringUtilsAndWordUtilsUsage { public static void main(String[] args) { // data setup String str1 = "" ; String str2 = " " ; String str3 = "\t" ; String str4 = null ; String str5 = "123" ; String str6 = "ABCDEFG" ; String str7 = "It feels good to use Jakarta Commons.\r\n" ; // check for empty strings System.out.println("==============================" ); System.out.println("Is str1 blank? " + StringUtils.isBlank(str1)); System.out.println("Is str2 blank? " + StringUtils.isBlank(str2)); System.out.println("Is str3 blank? " + StringUtils.isBlank(str3)); System.out.println("Is str4 blank? " + StringUtils.isBlank(str4)); // check for numerics System.out.println("==============================" ); System.out.println("Is str5 numeric? " + StringUtils.isNumeric(str5)); System.out.println("Is str6 numeric? " + StringUtils.isNumeric(str6)); // reverse strings / whole words System.out.println("==============================" ); System.out.println("str6: " + str6); System.out.println("str6 reversed: " + StringUtils.reverse(str6)); System.out.println("str7: " + str7); String str8 = StringUtils.chomp(str7); str8 = StringUtils.reverseDelimited(str8, ' ' ); System.out.println("str7 reversed whole words : \r\n" + str8); // build header (useful to print log messages that are easy to locate) System.out.println("==============================" ); System.out.println("print header:" ); String padding = StringUtils.repeat("=" , 50); String msg = StringUtils.center(" Customised Header " , 50, "%" ); Object[] raw = new Object[]{padding, msg, padding}; String header = StringUtils.join(raw, "\r\n" ); System.out.println(header); } }
输出的结果如下:
==============================
Is str1 blank? true
Is str2 blank? true
Is str3 blank? true
Is str4 blank? true
==============================
Is str5 numeric? true
Is str6 numeric? false
==============================
str6: ABCDEFG
str6 reversed: GFEDCBA
str7: It feels good to use Jakarta Commons.
str7 reversed whole words :
Commons. Jakarta use to good feels It
==============================
print header:
==================================================
%%%%%%%%%%%%%%% Customised Header %%%%%%%%%%%%%%%%
==================================================
从代码中我们可以大致了解到这个 StringUtils 类简单而强大的处理能力,从检查空串(对 null 的情况处理很得体),到分割子串,到生成格式化的字符串,使用都很简洁,也很直截了当。
四、commons.io包(StringUtils)方法集锦
1.文件内容拷贝:
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; public class FileCopyExample { public static void main(String[] args) { try { File src = new File( "test.dat" ); File dest = new File( "test.dat.bak" ); FileUtils.copyFile ( src, dest ); } catch ( IOException ioe ) { System. out .println( "Problem copying file." ); } try { File src = new File( "test.dat" ); File dir = new File( "./temp" ); FileUtils.copyFileToDirectory ( src, dir ); } catch ( IOException ioe ) { System. out .println( "Problem copying file to dir." ); } try { String string = "Blah blah blah" ; File dest = new File( "test.tmp" ); FileUtils.writeStringToFile ( dest, string, "ISO-8859-1" ); } catch ( IOException ioe ) { System. out .println( "Error writing out a String." ); } try { Writer writer = new FileWriter( "test.dat" ); InputStream inputStream =FileCopyExample. class . getClass().getResourceAsStream( "/io/web.xml" ); IOUtils.copy ( inputStream, writer ); writer.close(); inputStream.close(); } catch (IOException e) { System. out .println( "Error copying data" ); } try { File src = new File( "test.txt" ); OutputStream output = new FileOutputStream(src); InputStream inputStream =FileCopyExample. class . getClass().getResourceAsStream( "/io/web.xml" ); IOUtils.copy ( inputStream , output ); // writer.close(); inputStream .close(); output.close(); } catch (IOException e) { System. out .println( "Error copying data" ); } } }
2.文件删除:
File file = new File( ( "io/project.properties" ) ); String display = FileUtils. byteCountToDisplaySize ( file.length() ); System . out .println( "project.xml is " + display ); FileUtils.forceDelete (file)
3.读取取文本中的每一行:
import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileSystemUtils; import org.apache.commons.io.FileUtils; public class Test { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File((Test.class.getClass().getResource("/io/web.xml")).getFile()); List lines = FileUtils.readLines(file, "UTF-8"); for(int i=0;i<lines.size();i++) System.out.println(lines.get(i)); } }
五、commons包,网上的一些参考资料
http://www.blogjava.net/coolingverse/category/26252.html
http://www.open-open.com open文档-->我收藏的文档中,账号junjun1986
转:http://jun1986.iteye.com/blog/1401925