您的位置:首页 > 其它

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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: