自定義序列化和反序列化的java實現
import java.io.*;/**
- Created by jingqing.zhou on 2015/6/12.
- ByteArrayOutputStream :可以捕獲內存緩沖區的數據,轉換成字節數組。
- DataInputStream&DataOutputStream關心如何將數據從高層次的形式轉化成低層次的形式.
FileInputStream&FileOutputStream關心如何操作存儲單元以接受和產生數據。 */ public class ByteArrayIO { //序列化對象為String字符串,先對序列化后的結果進行BASE64編碼,否則不能直接進行反序列化 public static String writeObject(Object o) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(o); oos.flush(); oos.close(); bos.close(); //return new BASE64Encoder().encode(bos.toByteArray()); return new String(bos.toByteArray(), "ISO-8859-1");}
//反序列化String字符串為對象
public static Object readObject(String object) throws Exception{
//ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(object)); ByteArrayInputStream bis = new ByteArrayInputStream(object.getBytes("ISO-8859-1")); ObjectInputStream ois = new ObjectInputStream(bis); Object o = null; try { o = ois.readObject(); } catch(EOFException e) { System.err.print("read finished"); } bis.close(); ois.close(); return o;}
}</pre>
本文由用戶 gf67 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!