apache commons工具集代码详解
|
Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。
1、BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。
//1、 克隆对象
// 新创建一个普通Java Bean,用来作为被克隆的对象
public class Person {
private String name = "";
private String email = "";
private int age;
//省略 set,get方法
}
// 再创建一个Test类,其中在main方法中代码如下:
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
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)
2、Betwixt XML与Java对象之间相互转换。
//1、 将JavaBean转为XML内容
// 新创建一个Person类
public class Person{
private String name;
private int age;
/** Need to allow bean to be created via reflection */
public PersonBean() {
}
public PersonBean(String name,int age) {
this.name = name;
this.age = age;
}
//省略set,get方法
public String toString() {
return "PersonBean[name='" + name + "',age='" + age + "']";
}
}
//再创建一个WriteApp类:
import java.io.StringWriter;
import org.apache.commons.betwixt.io.BeanWriter;
public class WriteApp {
/**
* 创建一个例子Bean,并将它转化为XML.
*/
public static final void main(String [] args) throws Exception {
// 先创建一个StringWriter,我们将把它写入为一个字符串
StringWriter outputWriter = new StringWriter();
// Betwixt在这里仅仅是将Bean写入为一个片断
// 所以如果要想完整的XML内容,我们应该写入头格式
outputWriter.write(“<?xml version='1.0′ encoding='UTF-8′ ?>n”);
// 创建一个BeanWriter,其将写入到我们预备的stream中
BeanWriter beanWriter = new BeanWriter(outputWriter);
// 配置betwixt
// 更多详情请参考java docs 或最新的文档
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
// 如果这个地方不传入XML的根节点名,Betwixt将自己猜测是什么
// 但是让我们将例子Bean名作为根节点吧
beanWriter.write(“person”,new PersonBean(“John Smith”,21));
//输出结果
System.out.println(outputWriter.toString());
// Betwixt写的是片断而不是一个文档,所以不要自动的关闭掉writers或者streams,
//但这里仅仅是一个例子,不会做更多事情,所以可以关掉
outputWriter.close();
}
}
//2、 将XML转化为JavaBean
import java.io.StringReader;
import org.apache.commons.betwixt.io.BeanReader;
public class ReadApp {
public static final void main(String args[]) throws Exception{
// 先创建一个XML,由于这里仅是作为例子,所以我们硬编码了一段XML内容
StringReader xmlReader = new StringReader(
"<?xml version='1.0′ encoding='UTF-8′ ?> <person><age>25</age><name>James Smith</name></person>");
//创建BeanReader
BeanReader beanReader = new BeanReader();
//配置reader
beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanReader.getBindingConfiguration().setMapIDs(false);
//注册beans,以便betwixt知道XML将要被转化为一个什么Bean
beanReader.registerBeanClass("person",PersonBean.class);
//现在我们对XML进行解析
PersonBean person = (PersonBean) beanReader.parse(xmlReader);
//输出结果
System.out.println(person);
}
}
3、Codec 提供了一些公共的编解码实现,比如Base64,Hex,MD5,Phonetic and URLs等等。
//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);
}
4、Collections 对java.util的扩展封装,处理数据还是挺灵活的。 org.apache.commons.collections C Commons Collections自定义的一组公用的接口和工具类 org.apache.commons.collections.bag C 实现Bag接口的一组类 org.apache.commons.collections.bidimap C 实现BidiMap系列接口的一组类 org.apache.commons.collections.buffer C 实现Buffer接口的一组类 org.apache.commons.collections.collection C 实现java.util.Collection接口的一组类 org.apache.commons.collections.comparators C 实现java.util.Comparator接口的一组类 org.apache.commons.collections.functors C Commons Collections自定义的一组功能类 org.apache.commons.collections.iterators C 实现java.util.Iterator接口的一组类 org.apache.commons.collections.keyvalue C 实现集合和键/值映射相关的一组类 org.apache.commons.collections.list C 实现java.util.List接口的一组类 org.apache.commons.collections.map C 实现Map系列接口的一组类 org.apache.commons.collections.set C 实现Set系列接口的一组类
/**
* 得到集合里按顺序存放的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);
5、Compress commons compress中的打包、压缩类库。
//创建压缩对象
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();
6、Configuration 用来帮助处理配置文件的,支持很多种存储方式。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
