一个简单的序列化与反序列化工具类
1 import java.io.ByteArrayInputStream; 2 import java.io.ByteArrayOutputStream; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 import java.io.ObjectOutputStream; 6 7 public class SerializeUtil { 8 9 /** 10 * 序列化 11 */ 12 public static byte[] serialized(Object source) { 13 try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 14 ObjectOutputStream oos = new ObjectOutputStream(bos)) { 15 oos.writeObject(source); 16 oos.flush(); 17 byte[] result = bos.toByteArray(); 18 return result; 19 } catch (IOException e) { 20 e.printStackTrace(); 21 System.out.println("序列化失败!"); 22 } 23 return null; 24 } 25 26 /** 27 * 反序列化 28 */ 29 public static Object deserialized(byte[] source) { 30 try (ByteArrayInputStream bis = new ByteArrayInputStream(source); 31 ObjectInputStream ois = new ObjectInputStream(bis)) { 32 Object result = ois.readObject(); 33 return result; 34 } catch (IOException | ClassNotFoundException e) { 35 e.printStackTrace(); 36 System.out.println("反序列化失败!"); 37 } 38 return null; 39 } 40 41 }
byte[]在反序列化为Object的前提是byte[]是通过ObjectOutputStream序列化的,而且序列化与反序列化必须采用相同的方法,否则直接将一个任意的byte[]转换成Object时会报错,
错误信息为:java.io.StreamCorruptedException: invalid stream header: EFBFBDEF