Java代码 复制代码 收藏代码spinner.gif
  1. //序列化对象为String字符串,先对序列化后的结果进行BASE64编码,否则不能直接进行反序列化
  2. public static String writeObject(Object o) throws Exception {
  3. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  4. ObjectOutputStream oos = new ObjectOutputStream(bos);
  5. oos.writeObject(o);
  6. oos.flush();
  7. oos.close();
  8. bos.close();
  9. //return new BASE64Encoder().encode(bos.toByteArray());
  10. return new String(bos.toByteArray(), "ISO-8859-1");
  11. }
  12. //反序列化String字符串为对象
  13. public static Object readObject(String object) throws Exception{
  14. //ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(object));
  15. ByteArrayInputStream bis = new ByteArrayInputStream(object.getBytes("ISO-8859-1"));
  16. ObjectInputStream ois = new ObjectInputStream(bis);
  17. Object o = null;
  18. try {
  19. o = ois.readObject();
  20. } catch(EOFException e) {
  21. System.err.print("read finished");
  22. }
  23. bis.close();
  24. ois.close();
  25. return o;
  26. }