实例代码:
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("[email protected]"); 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()); } }
时间: 2024-10-28 19:43:49