Apache Commons工具集简介

转载出处http://zhoualine.iteye.com/blog/1770014,转载以备份

Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。

组件功能介绍
BeanUtils提供了对于JavaBean进行各种操作,克隆对象,属性等等.
BetwixtXML与Java对象之间相互转换.
Codec处理常用的编码方法的工具类包 例如DES、SHA1、MD5、Base64等.
Collectionsjava集合框架操作.
Compressjava提供文件打包 压缩类库.
Configuration一个java应用程序的配置管理类库.
DBCP提供数据库连接池服务.
DbUtils提供对jdbc 的操作封装来简化数据查询和记录读取操作.
Emailjava发送邮件 对javamail的封装.
FileUpload提供文件上传功能.
HttpClien提供HTTP客户端与服务器的各种通讯操作. 现在已改成HttpComponents
IOio工具的封装.
LangJava基本对象方法的工具类包 如:StringUtils,ArrayUtils等等.
Logging提供的是一个Java 的日志接口.
Validator提供了客户端和服务器端的数据验证框架.

1、BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。

Java代码

  1. //1、 克隆对象
  2. // 新创建一个普通Java Bean,用来作为被克隆的对象
  3. public class Person {
  4. private String name = "";
  5. private String email = "";
  6. private int age;
  7. //省略 set,get方法
  8. }
  9. // 再创建一个Test类,其中在main方法中代码如下:
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import org.apache.commons.beanutils.BeanUtils;
  14. import org.apache.commons.beanutils.ConvertUtils;
  15. public class Test {
  16. /**
  17. * @param args
  18. */
  19. public static void main(String[] args) {
  20. Person person = new Person();
  21. person.setName("tom");
  22. person.setAge(21);
  23. try {
  24. //克隆
  25. Person person2 = (Person)BeanUtils.cloneBean(person);
  26. System.out.println(person2.getName()+">>"+person2.getAge());
  27. } catch (IllegalAccessException e) {
  28. e.printStackTrace();
  29. } catch (InstantiationException e) {
  30. e.printStackTrace();
  31. } catch (InvocationTargetException e) {
  32. e.printStackTrace();
  33. } catch (NoSuchMethodException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. // 原理也是通过Java的反射机制来做的。
  39. // 2、 将一个Map对象转化为一个Bean
  40. // 这个Map对象的key必须与Bean的属性相对应。
  41. Map map = new HashMap();
  42. map.put("name","tom");
  43. map.put("email","tom@");
  44. map.put("age","21");
  45. //将map转化为一个Person对象
  46. Person person = new Person();
  47. BeanUtils.populate(person,map);
  48. // 通过上面的一行代码,此时person的属性就已经具有了上面所赋的值了。
  49. // 将一个Bean转化为一个Map对象了,如下:
  50. Map map = BeanUtils.describe(person)

2、Betwixt XML与Java对象之间相互转换。

Java代码

  1. //1、 将JavaBean转为XML内容
  2. // 新创建一个Person类
  3. public class Person{
  4. private String name;
  5. private int age;
  6. /** Need to allow bean to be created via reflection */
  7. public PersonBean() {
  8. }
  9. public PersonBean(String name, int age) {
  10. this.name = name;
  11. this.age = age;
  12. }
  13. //省略set, get方法
  14. public String toString() {
  15. return "PersonBean[name='" + name + "',age='" + age + "']";
  16. }
  17. }
  18. //再创建一个WriteApp类:
  19. import java.io.StringWriter;
  20. import org.apache.commons.betwixt.io.BeanWriter;
  21. public class WriteApp {
  22. /**
  23. * 创建一个例子Bean,并将它转化为XML.
  24. */
  25. public static final void main(String [] args) throws Exception {
  26. // 先创建一个StringWriter,我们将把它写入为一个字符串
  27. StringWriter outputWriter = new StringWriter();
  28. // Betwixt在这里仅仅是将Bean写入为一个片断
  29. // 所以如果要想完整的XML内容,我们应该写入头格式
  30. outputWriter.write(“<?xml version=’1.0′ encoding=’UTF-8′ ?>\n”);
  31. // 创建一个BeanWriter,其将写入到我们预备的stream中
  32. BeanWriter beanWriter = new BeanWriter(outputWriter);
  33. // 配置betwixt
  34. // 更多详情请参考java docs 或最新的文档
  35. beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
  36. beanWriter.getBindingConfiguration().setMapIDs(false);
  37. beanWriter.enablePrettyPrint();
  38. // 如果这个地方不传入XML的根节点名,Betwixt将自己猜测是什么
  39. // 但是让我们将例子Bean名作为根节点吧
  40. beanWriter.write(“person”, new PersonBean(“John Smith”, 21));
  41. //输出结果
  42. System.out.println(outputWriter.toString());
  43. // Betwixt写的是片断而不是一个文档,所以不要自动的关闭掉writers或者streams,
  44. //但这里仅仅是一个例子,不会做更多事情,所以可以关掉
  45. outputWriter.close();
  46. }
  47. }
  48. //2、 将XML转化为JavaBean
  49. import java.io.StringReader;
  50. import org.apache.commons.betwixt.io.BeanReader;
  51. public class ReadApp {
  52. public static final void main(String args[]) throws Exception{
  53. // 先创建一个XML,由于这里仅是作为例子,所以我们硬编码了一段XML内容
  54. StringReader xmlReader = new StringReader(
  55. "<?xml version=’1.0′ encoding=’UTF-8′ ?> <person><age>25</age><name>James Smith</name></person>");
  56. //创建BeanReader
  57. BeanReader beanReader = new BeanReader();
  58. //配置reader
  59. beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
  60. beanReader.getBindingConfiguration().setMapIDs(false);
  61. //注册beans,以便betwixt知道XML将要被转化为一个什么Bean
  62. beanReader.registerBeanClass("person", PersonBean.class);
  63. //现在我们对XML进行解析
  64. PersonBean person = (PersonBean) beanReader.parse(xmlReader);
  65. //输出结果
  66. System.out.println(person);
  67. }
  68. }

3、Codec 提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。

Java代码

  1. //Base64编解码
  2. private static String encodeTest(String str){
  3. Base64 base64 = new Base64();
  4. try {
  5. str = base64.encodeToString(str.getBytes("UTF-8"));
  6. } catch (UnsupportedEncodingException e) {
  7. e.printStackTrace();
  8. }
  9. System.out.println("Base64 编码后:"+str);
  10. return str;
  11. }
  12. private static void decodeTest(String str){
  13. Base64 base64 = new Base64();
  14. //str = Arrays.toString(Base64.decodeBase64(str));
  15. str = new String(Base64.decodeBase64(str));
  16. System.out.println("Base64 解码后:"+str);
  17. }

4、Collections 对java.util的扩展封装,处理数据还是挺灵活的。

org.apache.commons.collections – Commons Collections自定义的一组公用的接口和工具类

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系列接口的一组类

Java代码

  1. /**
  2. * 得到集合里按顺序存放的key之后的某一Key
  3. */
  4. OrderedMap map = new LinkedMap();
  5. map.put("FIVE", "5");
  6. map.put("SIX", "6");
  7. map.put("SEVEN", "7");
  8. map.firstKey(); // returns "FIVE"
  9. map.nextKey("FIVE"); // returns "SIX"
  10. map.nextKey("SIX"); // returns "SEVEN"
  11. /**
  12. * 通过key得到value
  13. * 通过value得到key
  14. * 将map里的key和value对调
  15. */
  16. BidiMap bidi = new TreeBidiMap();
  17. bidi.put("SIX", "6");
  18. bidi.get("SIX"); // returns "6"
  19. bidi.getKey("6"); // returns "SIX"
  20. // bidi.removeValue("6"); // removes the mapping
  21. BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped
  22. System.out.println(inverse);
  23. /**
  24. * 得到两个集合中相同的元素
  25. */
  26. List<String> list1 = new ArrayList<String>();
  27. list1.add("1");
  28. list1.add("2");
  29. list1.add("3");
  30. List<String> list2 = new ArrayList<String>();
  31. list2.add("2");
  32. list2.add("3");
  33. list2.add("5");
  34. Collection c = CollectionUtils.retainAll(list1, list2);
  35. System.out.println(c);

5、Compress commons compress中的打包、压缩类库。

Java代码

  1. //创建压缩对象
  2. ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");
  3. //要压缩的文件
  4. File f=new File("e:\\test.pdf");
  5. FileInputStream fis=new FileInputStream(f);
  6. //输出的对象 压缩的文件
  7. ZipArchiveOutputStream zipOutput=new ZipArchiveOutputStream(new File("e:\\test.zip"));
  8. zipOutput.putArchiveEntry(entry);
  9. int i=0,j;
  10. while((j=fis.read()) != -1)
  11. {
  12. zipOutput.write(j);
  13. i++;
  14. System.out.println(i);
  15. }
  16. zipOutput.closeArchiveEntry();
  17. zipOutput.close();
  18. fis.close();

6、Configuration 用来帮助处理配置文件的,支持很多种存储方式。

1. Properties files

2. XML documents

3. Property list files (.plist)

4. JNDI

5. JDBC Datasource

6. System properties

7. Applet parameters

8. Servlet parameters

Java代码

  1. //举一个Properties的简单例子
  2. # usergui.properties
  3. colors.background = #FFFFFF
  4. colors.foreground = #000080
  5. window.width = 500
  6. window.height = 300
  7. PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
  8. config.setProperty("colors.background", "#000000);
  9. config.save();
  10. config.save("usergui.backup.properties);//save a copy
  11. Integer integer = config.getInteger("window.width");

7、DBCP (Database Connection Pool)是一个依赖Jakarta commons-pool对象池机制的数据库连接池,Tomcat的数据源使用的就是DBCP。

Java代码

  1. import javax.sql.DataSource;
  2. import java.sql.Connection;
  3. import java.sql.Statement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import org.apache.commons.pool.ObjectPool;
  7. import org.apache.commons.pool.impl.GenericObjectPool;
  8. import org.apache.commons.dbcp.ConnectionFactory;
  9. import org.apache.commons.dbcp.PoolingDataSource;
  10. import org.apache.commons.dbcp.PoolableConnectionFactory;
  11. import org.apache.commons.dbcp.DriverManagerConnectionFactory;
  12. //官方示例
  13. public class PoolingDataSources {
  14. public static void main(String[] args) {
  15. System.out.println("加载jdbc驱动");
  16. try {
  17. Class.forName("oracle.jdbc.driver.OracleDriver");
  18. } catch (ClassNotFoundException e) {
  19. e.printStackTrace();
  20. }
  21. System.out.println("Done.");
  22. //
  23. System.out.println("设置数据源");
  24. DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");
  25. System.out.println("Done.");
  26. //
  27. Connection conn = null;
  28. Statement stmt = null;
  29. ResultSet rset = null;
  30. try {
  31. System.out.println("Creating connection.");
  32. conn = dataSource.getConnection();
  33. System.out.println("Creating statement.");
  34. stmt = conn.createStatement();
  35. System.out.println("Executing statement.");
  36. rset = stmt.executeQuery("select * from person");
  37. System.out.println("Results:");
  38. int numcols = rset.getMetaData().getColumnCount();
  39. while(rset.next()) {
  40. for(int i=0;i<=numcols;i++) {
  41. System.out.print("\t" + rset.getString(i));
  42. }
  43. System.out.println("");
  44. }
  45. } catch(SQLException e) {
  46. e.printStackTrace();
  47. } finally {
  48. try { if (rset != null) rset.close(); } catch(Exception e) { }
  49. try { if (stmt != null) stmt.close(); } catch(Exception e) { }
  50. try { if (conn != null) conn.close(); } catch(Exception e) { }
  51. }
  52. }
  53. public static DataSource setupDataSource(String connectURI) {
  54. //设置连接地址
  55. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
  56. connectURI, null);
  57. // 创建连接工厂
  58. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
  59. connectionFactory);
  60. //获取GenericObjectPool 连接的实例
  61. ObjectPool connectionPool = new GenericObjectPool(
  62. poolableConnectionFactory);
  63. // 创建 PoolingDriver
  64. PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
  65. return dataSource;
  66. }
  67. }

8、DbUtils Apache组织提供的一个资源JDBC工具类库,它是对JDBC的简单封装,对传统操作数据库的类进行二次封装,可以把结果集转化成List。,同时也不影响程序的性能。

DbUtils类:启动类

ResultSetHandler接口:转换类型接口

MapListHandler类:实现类,把记录转化成List

BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象

Qrery Runner类:执行SQL语句的类

Java代码

  1. import org.apache.commons.dbutils.DbUtils;
  2. import org.apache.commons.dbutils.QueryRunner;
  3. import org.apache.commons.dbutils.handlers.BeanListHandler;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.SQLException;
  7. import java.util.List;
  8. //转换成list
  9. public class BeanLists {
  10. public static void main(String[] args) {
  11. Connection conn = null;
  12. String url = "jdbc:mysql://localhost:3306/ptest";
  13. String jdbcDriver = "com.mysql.jdbc.Driver";
  14. String user = "root";
  15. String password = "ptest";
  16. DbUtils.loadDriver(jdbcDriver);
  17. try {
  18. conn = DriverManager.getConnection(url, user, password);
  19. QueryRunner qr = new QueryRunner();
  20. List results = (List) qr.query(conn, "select id,name from person", new BeanListHandler(Person.class));
  21. for (int i = 0; i < results.size(); i++) {
  22. Person p = (Person) results.get(i);
  23. System.out.println("id:" + p.getId() + ",name:" + p.getName());
  24. }
  25. } catch (SQLException e) {
  26. e.printStackTrace();
  27. } finally {
  28. DbUtils.closeQuietly(conn);
  29. }
  30. }
  31. }
  32. public class Person{
  33. private Integer id;
  34. private String name;
  35. //省略set, get方法
  36. }
  37. import org.apache.commons.dbutils.DbUtils;
  38. import org.apache.commons.dbutils.QueryRunner;
  39. import org.apache.commons.dbutils.handlers.MapListHandler;
  40. import java.sql.Connection;
  41. import java.sql.DriverManager;
  42. import java.sql.SQLException;
  43. import java.util.List;
  44. import java.util.Map;
  45. //转换成map
  46. public class MapLists {
  47. public static void main(String[] args) {
  48. Connection conn = null;
  49. String url = "jdbc:mysql://localhost:3306/ptest";
  50. String jdbcDriver = "com.mysql.jdbc.Driver";
  51. String user = "root";
  52. String password = "ptest";
  53. DbUtils.loadDriver(jdbcDriver);
  54. try {
  55. conn = DriverManager.getConnection(url, user, password);
  56. QueryRunner qr = new QueryRunner();
  57. List results = (List) qr.query(conn, "select id,name from person", new MapListHandler());
  58. for (int i = 0; i < results.size(); i++) {
  59. Map map = (Map) results.get(i);
  60. System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));
  61. }
  62. } catch (SQLException e) {
  63. e.printStackTrace();
  64. } finally {
  65. DbUtils.closeQuietly(conn);
  66. }
  67. }
  68. }

9、Email 提供的一个开源的API,是对javamail的封装。

Java代码

  1. //用commons email发送邮件
  2. public static void main(String args[]){
  3. Email email = new SimpleEmail();
  4. email.setHostName("smtp.googlemail.com");
  5. email.setSmtpPort(465);
  6. email.setAuthenticator(new DefaultAuthenticator("username", "password"));
  7. email.setSSLOnConnect(true);
  8. email.setFrom("user@gmail.com");
  9. email.setSubject("TestMail");
  10. email.setMsg("This is a test mail ... :-)");
  11. email.addTo("foo@bar.com");
  12. email.send();
  13. }

10、FileUpload java web文件上传功能。

Java代码

  1. //官方示例:
  2. //* 检查请求是否含有上传文件
  3. // Check that we have a file upload request
  4. boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  5. //现在我们得到了items的列表
  6. //如果你的应用近于最简单的情况,上面的处理就够了。但我们有时候还是需要更多的控制。
  7. //下面提供了几种控制选择:
  8. // Create a factory for disk-based file items
  9. DiskFileItemFactory factory = new DiskFileItemFactory();
  10. // Set factory constraints
  11. factory.setSizeThreshold(yourMaxMemorySize);
  12. factory.setRepository(yourTempDirectory);
  13. // Create a new file upload handler
  14. ServletFileUpload upload = new ServletFileUpload(factory);
  15. // 设置最大上传大小
  16. upload.setSizeMax(yourMaxRequestSize);
  17. // 解析所有请求
  18. List /* FileItem */ items = upload.parseRequest(request);
  19. // Create a factory for disk-based file items
  20. DiskFileItemFactory factory = new DiskFileItemFactory(
  21. yourMaxMemorySize, yourTempDirectory);
  22. //一旦解析完成,你需要进一步处理item的列表。
  23. // Process the uploaded items
  24. Iterator iter = items.iterator();
  25. while (iter.hasNext()) {
  26. FileItem item = (FileItem) iter.next();
  27. if (item.isFormField()) {
  28. processFormField(item);
  29. } else {
  30. processUploadedFile(item);
  31. }
  32. }
  33. //区分数据是否为简单的表单数据,如果是简单的数据:
  34. // processFormField
  35. if (item.isFormField()) {
  36. String name = item.getFieldName();
  37. String value = item.getString();
  38. //...省略步骤
  39. }
  40. //如果是提交的文件:
  41. // processUploadedFile
  42. if (!item.isFormField()) {
  43. String fieldName = item.getFieldName();
  44. String fileName = item.getName();
  45. String contentType = item.getContentType();
  46. boolean isInMemory = item.isInMemory();
  47. long sizeInBytes = item.getSize();
  48. //...省略步骤
  49. }
  50. //对于这些item,我们通常要把它们写入文件,或转为一个流
  51. // Process a file upload
  52. if (writeToFile) {
  53. File uploadedFile = new File(...);
  54. item.write(uploadedFile);
  55. } else {
  56. InputStream uploadedStream = item.getInputStream();
  57. //...省略步骤
  58. uploadedStream.close();
  59. }
  60. //或转为字节数组保存在内存中:
  61. // Process a file upload in memory
  62. byte[] data = item.get();
  63. //...省略步骤
  64. //如果这个文件真的很大,你可能会希望向用户报告到底传了多少到服务端,让用户了解上传的过程
  65. //Create a progress listener
  66. ProgressListener progressListener = new ProgressListener(){
  67. public void update(long pBytesRead, long pContentLength, int pItems) {
  68. System.out.println("We are currently reading item " + pItems);
  69. if (pContentLength == -1) {
  70. System.out.println("So far, " + pBytesRead + " bytes have been read.");
  71. } else {
  72. System.out.println("So far, " + pBytesRead + " of " + pContentLength
  73. + " bytes have been read.");
  74. }
  75. }
  76. };
  77. upload.setProgressListener(progressListener);

11、HttpClien 基于HttpCore实 现的一个HTTP/1.1兼容的HTTP客户端,它提供了一系列可重用的客户端身份验证、HTTP状态保持、HTTP连接管理module。

Java代码

  1. //GET方法
  2. import java.io.IOException;
  3. import org.apache.commons.httpclient.*;
  4. import org.apache.commons.httpclient.methods.GetMethod;
  5. import org.apache.commons.httpclient.params.HttpMethodParams;
  6. public class GetSample{
  7. public static void main(String[] args) {
  8. // 构造HttpClient的实例
  9. HttpClient httpClient = new HttpClient();
  10. // 创建GET方法的实例
  11. GetMethod getMethod = new GetMethod("http://www.ibm.com");
  12. // 使用系统提供的默认的恢复策略
  13. getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
  14. new DefaultHttpMethodRetryHandler());
  15. try {
  16. // 执行getMethod
  17. int statusCode = httpClient.executeMethod(getMethod);
  18. if (statusCode != HttpStatus.SC_OK) {
  19. System.err.println("Method failed: "
  20. + getMethod.getStatusLine());
  21. }
  22. // 读取内容
  23. byte[] responseBody = getMethod.getResponseBody();
  24. // 处理内容
  25. System.out.println(new String(responseBody));
  26. } catch (HttpException e) {
  27. // 发生致命的异常,可能是协议不对或者返回的内容有问题
  28. System.out.println("Please check your provided http address!");
  29. e.printStackTrace();
  30. } catch (IOException e) {
  31. // 发生网络异常
  32. e.printStackTrace();
  33. } finally {
  34. // 释放连接
  35. getMethod.releaseConnection();
  36. }
  37. }
  38. }
  39. //POST方法
  40. import java.io.IOException;
  41. import org.apache.commons.httpclient.*;
  42. import org.apache.commons.httpclient.methods.PostMethod;
  43. import org.apache.commons.httpclient.params.HttpMethodParams;
  44. public class PostSample{
  45. public static void main(String[] args) {
  46. // 构造HttpClient的实例
  47. HttpClient httpClient = new HttpClient();
  48. // 创建POST方法的实例
  49. String url = "http://www.oracle.com/";
  50. PostMethod postMethod = new PostMethod(url);
  51. // 填入各个表单域的值
  52. NameValuePair[] data = { new NameValuePair("id", "youUserName"),
  53. new NameValuePair("passwd", "yourPwd") };
  54. // 将表单的值放入postMethod中
  55. postMethod.setRequestBody(data);
  56. // 执行postMethod
  57. int statusCode = httpClient.executeMethod(postMethod);
  58. // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
  59. // 301或者302
  60. if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
  61. statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
  62. // 从头中取出转向的地址
  63. Header locationHeader = postMethod.getResponseHeader("location");
  64. String location = null;
  65. if (locationHeader != null) {
  66. location = locationHeader.getValue();
  67. System.out.println("The page was redirected to:" + location);
  68. } else {
  69. System.err.println("Location field value is null.");
  70. }
  71. return;
  72. }
  73. }
  74. }

12、IO 对java.io的扩展 操作文件非常方便。

Java代码

  1. //1.读取Stream
  2. //标准代码:
  3. InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
  4. try {
  5. InputStreamReader inR = new InputStreamReader( in );
  6. BufferedReader buf = new BufferedReader( inR );
  7. String line;
  8. while ( ( line = buf.readLine() ) != null ) {
  9. System.out.println( line );
  10. }
  11. } finally {
  12. in.close();
  13. }
  14. //使用IOUtils
  15. InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
  16. try {
  17. System.out.println( IOUtils.toString( in ) );
  18. } finally {
  19. IOUtils.closeQuietly(in);
  20. }
  21. //2.读取文件
  22. File file = new File("/commons/io/project.properties");
  23. List lines = FileUtils.readLines(file, "UTF-8");
  24. //3.察看剩余空间
  25. long freeSpace = FileSystemUtils.freeSpace("C:/");

13、Lang 主要是一些公共的工具集合,比如对字符、数组的操作等等。

Java代码

  1. // 1 合并两个数组: org.apache.commons.lang. ArrayUtils
  2. // 有时我们需要将两个数组合并为一个数组,用ArrayUtils就非常方便,示例如下:
  3. private static void testArr() {
  4. String[] s1 = new String[] { "1", "2", "3" };
  5. String[] s2 = new String[] { "a", "b", "c" };
  6. String[] s = (String[]) ArrayUtils.addAll(s1, s2);
  7. for (int i = 0; i < s.length; i++) {
  8. System.out.println(s[i]);
  9. }
  10. String str = ArrayUtils.toString(s);
  11. str = str.substring(1, str.length() - 1);
  12. System.out.println(str + ">>" + str.length());
  13. }
  14. //2 截取从from开始字符串
  15. StringUtils.substringAfter("SELECT * FROM PERSON ", "from");
  16. //3 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和 请注意
  17. StringUtils.isNumeric("454534"); //返回true
  18. //4.取得类名
  19. System.out.println(ClassUtils.getShortClassName(Test.class));
  20. //取得其包名
  21. System.out.println(ClassUtils.getPackageName(Test.class));
  22. //5.NumberUtils
  23. System.out.println(NumberUtils.stringToInt("6"));
  24. //6.五位的随机字母和数字
  25. System.out.println(RandomStringUtils.randomAlphanumeric(5));
  26. //7.StringEscapeUtils
  27. System.out.println(StringEscapeUtils.escapeHtml("<html>"));
  28. //输出结果为&lt;html&gt;
  29. System.out.println(StringEscapeUtils.escapeJava("String"));
  30. //8.StringUtils,判断是否是空格字符
  31. System.out.println(StringUtils.isBlank(" "));
  32. //将数组中的内容以,分隔
  33. System.out.println(StringUtils.join(test,","));
  34. //在右边加下字符,使之总长度为6
  35. System.out.println(StringUtils.rightPad("abc", 6, 'T'));
  36. //首字母大写
  37. System.out.println(StringUtils.capitalize("abc"));
  38. //Deletes all whitespaces from a String 删除所有空格
  39. System.out.println( StringUtils.deleteWhitespace(" ab c "));
  40. //判断是否包含这个字符
  41. System.out.println( StringUtils.contains("abc", "ba"));
  42. //表示左边两个字符
  43. System.out.println( StringUtils.left("abc", 2));
  44. System.out.println(NumberUtils.stringToInt("33"));

14、Logging 提供的是一个Java 的日志接口,同时兼顾轻量级和不依赖于具体的日志实现工具。

Java代码

  1. import org.apache.commons.logging.Log;
  2. import org.apache.commons.logging.LogFactory;
  3. public class CommonLogTest {
  4. private static Log log = LogFactory.getLog(CommonLogTest.class);
  5. //日志打印
  6. public static void main(String[] args) {
  7. log.error("ERROR");
  8. log.debug("DEBUG");
  9. log.warn("WARN");
  10. log.info("INFO");
  11. log.trace("TRACE");
  12. System.out.println(log.getClass());
  13. }
  14. }

15、Validator 通用验证系统,该组件提供了客户端和服务器端的数据验证框架。

验证日期

Java代码

  1. // 获取日期验证
  2. DateValidator validator = DateValidator.getInstance();
  3. // 验证/转换日期
  4. Date fooDate = validator.validate(fooString, "dd/MM/yyyy");
  5. if (fooDate == null) {
  6. // 错误 不是日期
  7. return;
  8. }

表达式验证

Java代码

  1. // 设置参数
  2. boolean caseSensitive = false;
  3. String regex1 = "^([A-Z]*)(?:\\-)([A-Z]*)*$"
  4. String regex2 = "^([A-Z]*)$";
  5. String[] regexs = new String[] {regex1, regex1};
  6. // 创建验证
  7. RegexValidator validator = new RegexValidator(regexs, caseSensitive);
  8. // 验证返回boolean
  9. boolean valid = validator.isValid("abc-def");
  10. // 验证返回字符串
  11. String result = validator.validate("abc-def");
  12. // 验证返回数组
  13. String[] groups = validator.match("abc-def");

配置文件中使用验证

Xml代码

  1. <form-validation>
  2. <global>
  3. <validator name="required"
  4. classname="org.apache.commons.validator.TestValidator"
  5. method="validateRequired"
  6. methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
  7. </global>
  8. <formset>
  9. </formset>
  10. </form-validation>
  11. 添加姓名验证.
  12. <form-validation>
  13. <global>
  14. <validator name="required"
  15. classname="org.apache.commons.validator.TestValidator"
  16. method="validateRequired"
  17. methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
  18. </global>
  19. <formset>
  20. <form name="nameForm">
  21. <field property="firstName" depends="required">
  22. <arg0 key="nameForm.firstname.displayname"/>
  23. </field>
  24. <field property="lastName" depends="required">
  25. <arg0 key="nameForm.lastname.displayname"/>
  26. </field>
  27. </form>
  28. </formset>
  29. </form-validation>

验证类

Java代码

  1. Excerpts from org.apache.commons.validator.RequiredNameTest
  2. //加载验证配置文件
  3. InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");
  4. ValidatorResources resources = new ValidatorResources(in);
  5. //这个是自己创建的bean 我这里省略了
  6. Name name = new Name();
  7. Validator validator = new Validator(resources, "nameForm");
  8. //设置参数
  9. validator.setParameter(Validator.BEAN_PARAM, name);
  10. Map results = null;
  11. //验证
  12. results = validator.validate();
  13. if (results.get("firstName") == null) {
  14. //验证成功
  15. } else {
  16. //有错误 int errors = ((Integer)results.get("firstName")).intValue();
  17. }