java開發中序列化與還原序列化起到的作用,java序列化
基本概念:
序列化是將對象狀態轉換為可保持或傳輸的格式的過程。與序列化相對的是還原序列化,它將流轉換為對象。這兩個過程結合起來,可以輕鬆地儲存和傳輸資料。
特別在網路傳輸中,它的作用顯得尤為重要。我們可以把一個類實現序列化,然後在另一端通過還原序列化可以得到該對象
例如:我們可以序列化一個對象,不過這個對象要實現序列化方法,並產生序列化號。
這是對一個對象進行序列化和還原序列化的過程:
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();}}