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;
} </pre>下面是一個擴展(對集合的序列化和反序列化):<pre class="brush:java; toolbar: true; auto-links: false;"> 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();
}
} </pre> <p></p>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!