java对象的序列化与反序列化
java对象的序列化与反序列化
package com.linusiyu.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; @SuppressWarnings("restriction") public class DataTransferObjectSerializer { /** * 序列化对象 */ public static String serializeObject(Object obj) { ObjectOutputStream objOut = null; if(obj==null){ return null; } try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); objOut = new ObjectOutputStream(byteOut); objOut.writeObject(obj); return new sun.misc.BASE64Encoder().encode(byteOut.toByteArray()); } catch (Exception e) { } finally { if (objOut != null) {try {objOut.close();} catch (IOException e) {}} } } /** * 反序列化对象 */ public static Object deserializeObject(String values) { ObjectInputStream objIn = null; if(values==null){ return null; } try { byte[] valueByte = new sun.misc.BASE64Decoder().decodeBuffer(values); ByteArrayInputStream byteIn = new ByteArrayInputStream(valueByte); objIn = new ObjectInputStream(byteIn); return objIn.readObject(); } catch (Exception e) { throw new RuntimeException(e.getMessage(),e); } finally { if (objIn != null) {try {objIn.close();} catch(IOException e){}} } } public static void main(String[] args) { P obj = new P(); String objStr = serializeObject(obj); System.out.println(objStr); P p = (P) deserializeObject(objStr); System.out.println(p.getA()); System.out.println(p.getB()); } } class P implements Serializable{ private static final long serialVersionUID = 1L; private String a = "hello serializable"; private int b = 5; public String getA() { return a; } public int getB() { return b; } }