这个类中提供了对象序列化与反序列化的方法,在实际的项目中会经常被用到。
1 import java.io.*; 2 3 public class SerializationUtils { 4 5 //把一个对象序列化 6 public static byte[] serialize(Object state) { 7 ObjectOutputStream oos = null; 8 try { 9 ByteArrayOutputStream bos = new ByteArrayOutputStream(512); 10 oos = new ObjectOutputStream(bos); 11 oos.writeObject(state); 12 oos.flush(); 13 return bos.toByteArray(); 14 } 15 catch (IOException e) { 16 throw new IllegalArgumentException(e); 17 } 18 finally { 19 if (oos != null) { 20 try { 21 oos.close(); 22 } 23 catch (IOException e) { 24 // eat it 25 } 26 } 27 } 28 } 29 30 //把一个对象反序列化 31 public static <T> T deserialize(byte[] byteArray) { 32 ObjectInputStream oip = null; 33 try { 34 oip = new ObjectInputStream(new ByteArrayInputStream(byteArray)); 35 @SuppressWarnings("unchecked") 36 T result = (T) oip.readObject(); 37 return result; 38 } 39 catch (IOException e) { 40 throw new IllegalArgumentException(e); 41 } 42 catch (ClassNotFoundException e) { 43 throw new IllegalArgumentException(e); 44 } 45 finally { 46 if (oip != null) { 47 try { 48 oip.close(); 49 } 50 catch (IOException e) { 51 // eat it 52 } 53 } 54 } 55 } 56 57 }