SerializeUtil.java 922 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package cn.com.lzt.common.util;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. public class SerializeUtil {
  7. public static byte[] serialize(Object object) {
  8. ObjectOutputStream oos = null;
  9. ByteArrayOutputStream baos = null;
  10. try {
  11. // 序列化
  12. baos = new ByteArrayOutputStream();
  13. oos = new ObjectOutputStream(baos);
  14. oos.writeObject(object);
  15. byte[] bytes = baos.toByteArray();
  16. return bytes;
  17. } catch (Exception e) {
  18. throw new RuntimeException(e.getMessage(), e);
  19. }
  20. }
  21. public static Object unserialize(byte[] bytes) {
  22. ByteArrayInputStream bais = null;
  23. try {
  24. // 反序列化
  25. bais = new ByteArrayInputStream(bytes);
  26. ObjectInputStream ois = new ObjectInputStream(bais);
  27. return ois.readObject();
  28. } catch (Exception e) {
  29. throw new RuntimeException(e.getMessage(), e);
  30. }
  31. }
  32. }