这是对一个对象进行序列化和反序列化的过程:
public static byte[] serializeObj(Object object){ if (object == null) { throw new NullPointerException("Can't serialize null"); } byte[] rv = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); os.writeObject(object); os.writeObject(null); os.close(); bos.close(); rv = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { try { if (os != null) { os.flush(); os.close(); } if (bos != null) { bos.flush(); bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return rv; } @SuppressWarnings("unchecked") public static <T>T deserializeObj(byte[] in,Class<T> clazz) { ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); while (true) { T o = (T) is.readObject(); if (o == null) { break; } else { return o; } } } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (bis != null) { bis.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }
public static <T>byte[] serializeList(List<T> value ,Class<T> clazz) { if (value == null) { throw new NullPointerException("Can't serialize null"); } byte[] rv = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); for (T t : value) { os.writeObject(t); } os.writeObject(null); os.close(); bos.close(); rv = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { try { if (os != null) { os.flush(); os.close(); } if (bos != null) { bos.flush(); bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return rv; } @SuppressWarnings("unchecked") public static <T> List<T> deserializeList(byte[] in,Class<T> clazz) { List<T> list = new ArrayList<T>(); ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); while (true) { T o = (T) is.readObject(); if (o == null) { break; } else { list.add(o); } } } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (bis != null) { bis.close(); } } catch (IOException e) { e.printStackTrace(); } }
原文地址:http://blog.csdn.net/u012516914/article/details/41009403