pojo的序列化和反序列化
2015-10-20 12:31
411 查看
实例代码:
package com.lky.pojo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import org.junit.Test; /** * @Title: Serializer.java * @Package com.lky.pojo * @Description:将数据类型T序列化和反序列化(T 类型要实现 Serializable接口) * @author lky * @date 2015年10月20日 上午11:38:12 * @version V1.0 */ public class Serializer<T> { public byte[] ObjectToByteArray(T obj) { byte[] bytes = null; ByteArrayOutputStream baos = null;//用来缓存数据,向它的内部缓冲区写入数据,缓冲区自动增长(字节流----->字节数组) ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream();// 声明一个字节数组输出流 oos = new ObjectOutputStream(baos);// 声明对象字节输出流 oos.writeObject(obj); oos.flush(); bytes = baos.toByteArray();// 转化为字节数组 } catch (Exception e) { e.printStackTrace(); } finally { try { if (oos != null) { oos.close(); } if (baos != null) { baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return bytes; } @SuppressWarnings("unchecked") public T ByteArrayToObject(byte[] obj) { T student = null; ByteArrayInputStream bais = null;//从字节数组中读入到字节流(字节数组------->字节流) ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(obj); ois = new ObjectInputStream(bais); student = (T) ois.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ois != null) { ois.close(); } if (bais != null) { bais.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return student; } @Test public void testSerializer() throws UnsupportedEncodingException { Student student = new Student(); student.setEmail("1411075450@qq.com"); student.setName("lky"); student.setPassword("lky"); // byte[] result = new Serializer<Student>().ObjectToByteArray(student); // System.out.println(new Serializer<Student>().ByteArrayToObject(result).toString()); // byte[] result = new Serializer<String>().ObjectToByteArray("lky"); // System.out.println(new Serializer<String>().ByteArrayToObject(result).toString()); byte[] result = new Serializer<Integer>().ObjectToByteArray(Integer.valueOf(100)); System.out.println(new Serializer<Integer>().ByteArrayToObject(result).toString()); } }
相关文章推荐
- POJ 2752 既是前缀又是后缀的子串 (kmp)
- 常用js正则表达式
- 终极 Shell——ZSH
- java核心技术之IO流(六)DataInputStream和DataOutputStream
- java记——函数调用输出倒序数
- jsp中select的onchange事件用法实例
- mac jenkins环境安装及jenkins使用(未完待续)
- 我的第一个web应用开发搭建-环境配置
- 关于andrio更新图片后手机端不显示
- C提高(4):
- IOS-TextField知多少
- NSParameterAssert延伸出去的理解
- 赤裸裸的splay平衡树
- Java类的连接与初始化 (及2013阿里初始化笔试题解析)
- KMP算法实现
- nohup 输出重定向
- 读取日志文件进行用户数据进库不完整补漏
- mysql 查找重复的字段,并删除记录只保留一条
- 【测试】Gunicorn , uWSGI同步异步测试以及应用场景总结
- 【测试】Gunicorn , uWSGI同步异步测试以及应用场景总结