序列化一个对象,反序列化一个对象就是如此
Java代码
1 package com.digican.utils; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.IOException; 6 import java.io.ObjectInputStream; 7 import java.io.ObjectOutputStream; 8 9 import com.digican.javabean.TestBean; 10 11 public class ObjectAndByte { 12 13 /** 14 * 对象转数组 15 * @param obj 16 * @return 17 */ 18 public byte[] toByteArray (Object obj) { 19 byte[] bytes = null; 20 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 21 try { 22 ObjectOutputStream oos = new ObjectOutputStream(bos); 23 oos.writeObject(obj); 24 oos.flush(); 25 bytes = bos.toByteArray (); 26 oos.close(); 27 bos.close(); 28 } catch (IOException ex) { 29 ex.printStackTrace(); 30 } 31 return bytes; 32 } 33 34 /** 35 * 数组转对象 36 * @param bytes 37 * @return 38 */ 39 public Object toObject (byte[] bytes) { 40 Object obj = null; 41 try { 42 ByteArrayInputStream bis = new ByteArrayInputStream (bytes); 43 ObjectInputStream ois = new ObjectInputStream (bis); 44 obj = ois.readObject(); 45 ois.close(); 46 bis.close(); 47 } catch (IOException ex) { 48 ex.printStackTrace(); 49 } catch (ClassNotFoundException ex) { 50 ex.printStackTrace(); 51 } 52 return obj; 53 } 54 55 public static void main(String[] args) { 56 TestBean tb = new TestBean(); 57 tb.setName("daqing"); 58 tb.setValue("1234567890"); 59 60 ObjectAndByte oa = new ObjectAndByte(); 61 byte[] b = oa.toByteArray(tb); 62 System.out.println(new String(b)); 63 64 System.out.println("======================================="); 65 66 TestBean teb = (TestBean) oa.toObject(b); 67 System.out.println(teb.getName()); 68 System.out.println(teb.getValue()); 69 } 70 71 }
1 package com.digican.javabean; 2 3 import java.io.Serializable; 4 5 public class TestBean implements Serializable{ 6 7 private String name; 8 9 private String value; 10 11 public String getName() { 12 return name; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 public String getValue() { 20 return value; 21 } 22 23 public void setValue(String value) { 24 this.value = value; 25 } 26 27 }
源自:https://www.cnblogs.com/cpcpc/archive/2011/09/05/2167886.html