个人专题目录
Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。
组件 | 功能介绍 |
---|---|
BeanUtils | 提供了对于JavaBean进行各种操作,克隆对象,属性等等. |
Betwixt | XML与Java对象之间相互转换. |
Codec | 处理常用的编码方法的工具类包 例如DES、SHA1、MD5、Base64等. |
Collections | java集合框架操作. |
Compress | java提供文件打包 压缩类库. |
Configuration | 一个java应用程序的配置管理类库. |
DBCP | 提供数据库连接池服务. |
DbUtils | 提供对jdbc 的操作封装来简化数据查询和记录读取操作. |
java发送邮件 对javamail的封装. | |
FileUpload | 提供文件上传功能. |
HttpClien | 提供HTTP客户端与服务器的各种通讯操作. 现在已改成HttpComponents |
IO | io工具的封装. |
Lang | Java基本对象方法的工具类包 如:StringUtils,ArrayUtils等等. |
Logging | 提供的是一个Java 的日志接口. |
Validator | 提供了客户端和服务器端的数据验证框架. |
BeanUtils
提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。
Java代码
// 新创建一个普通Java Bean,用来作为被克隆的对象
public class Person {
private String name = "";
private String email = "";
private int age;
//省略 set,get方法
}
Person person = new Person();
person.setName("tom");
person.setAge(21);
try {
//克隆
Person person2 = (Person) BeanUtils.cloneBean(person);
System.out.println(person2.getName() + ">>" + person2.getAge());
} catch (
IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
// 原理也是通过Java的反射机制来做的。
// 2、 将一个Map对象转化为一个Bean
// 这个Map对象的key必须与Bean的属性相对应。
Map map = new HashMap();
map.put("name", "tom");
map.put("email", "tom@");
map.put("age", "21");
//将map转化为一个Person对象
Person person = new Person();
BeanUtils.populate(person, map);
// 通过上面的一行代码,此时person的属性就已经具有了上面所赋的值了。
// 将一个Bean转化为一个Map对象了,如下:
Map map = BeanUtils.describe(person)
Codec
提供了一些公共的编解码实现,比如Base64, Hex, MD5,Phonetic and URLs等等。
Java代码
//Base64编解码
private static String encodeTest(String str) {
Base64 base64 = new Base64();
try {
str = base64.encodeToString(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("Base64 编码后:" + str);
return str;
}
private static void decodeTest(String str) {
Base64 base64 = new Base64();
//str = Arrays.toString(Base64.decodeBase64(str));
str = new String(Base64.decodeBase64(str));
System.out.println("Base64 解码后:" + str);
}
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代码
/**
* 得到集合里按顺序存放的key之后的某一Key
*/
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"
/**
* 通过key得到value
* 通过value得到key
* 将map里的key和value对调
*/
BidiMap bidi = new TreeBidiMap();
bidi.put("SIX", "6");
bidi.get("SIX"); // returns "6"
bidi.getKey("6"); // returns "SIX"
// bidi.removeValue("6"); // removes the mapping
BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped
System.out.println(inverse);
/**
* 得到两个集合中相同的元素
*/
List<String> list1 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
List<String> list2 = new ArrayList<String>();
list2.add("2");
list2.add("3");
list2.add("5");
Collection c = CollectionUtils.retainAll(list1, list2);
System.out.println(c);
Compress
commons compress中的打包、压缩类库。
Java代码
//创建压缩对象
ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");
//要压缩的文件
File f = new File("e:\test.pdf");
FileInputStream fis = new FileInputStream(f);
//输出的对象 压缩的文件
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("e:\test.zip"));
zipOutput.putArchiveEntry(entry);
int i = 0, j;
while ((j = fis.read()) != -1) {
zipOutput.write(j);
i++;
System.out.println(i);
}
zipOutput.closeArchiveEntry();
zipOutput.close();
fis.close();
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代码
//举一个Properties的简单例子
# usergui.properties
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");
DBCP
(Database Connection Pool)是一个依赖Jakarta commons-pool对象池机制的数据库连接池,Tomcat的数据源使用的就是DBCP。
//官方示例
public class PoolingDataSources {
public static void main(String[] args) {
System.out.println("加载jdbc驱动");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Done.");
//
System.out.println("设置数据源");
DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");
System.out.println("Done.");
//
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
System.out.println("Creating connection.");
conn = dataSource.getConnection();
System.out.println("Creating statement.");
stmt = conn.createStatement();
System.out.println("Executing statement.");
rset = stmt.executeQuery("select * from person");
System.out.println("Results:");
int numcols = rset.getMetaData().getColumnCount();
while (rset.next()) {
for (int i = 0; i <= numcols; i++) {
System.out.print("\t" + rset.getString(i));
}
System.out.println("");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rset != null) rset.close();
} catch (Exception e) {
}
try {
if (stmt != null) stmt.close();
} catch (Exception e) {
}
try {
if (conn != null) conn.close();
} catch (Exception e) {
}
}
}
public static DataSource setupDataSource(String connectURI) {
//设置连接地址
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
connectURI, null);
// 创建连接工厂
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
connectionFactory);
//获取GenericObjectPool 连接的实例
ObjectPool connectionPool = new GenericObjectPool(
poolableConnectionFactory);
// 创建 PoolingDriver
PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
return dataSource;
}
}
DbUtils
Apache组织提供的一个资源JDBC工具类库,它是对JDBC的简单封装,对传统操作数据库的类进行二次封装,可以把结果集转化成List。,同时也不影响程序的性能。
DbUtils类:启动类
ResultSetHandler接口:转换类型接口
MapListHandler类:实现类,把记录转化成List
BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象
Qrery Runner类:执行SQL语句的类
public class BeanLists {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/ptest";
String jdbcDriver = "com.mysql.jdbc.Driver";
String user = "root";
String password = "ptest";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from person", new BeanListHandler(Person.class));
for (int i = 0; i < results.size(); i++) {
Person p = (Person) results.get(i);
System.out.println("id:" + p.getId() + ",name:" + p.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}