歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java對象---序列化與反序列化

Java對象---序列化與反序列化

日期:2017/3/1 9:19:09   编辑:Linux編程

Java對象---序列化與反序列化

private static final String TEMP_ENCODING = "ISO-8859-1";
private static final String DEFAULT_ENCODING = "UTF-8";

/**
* 把java對象序列化成字符串
* @param obj
* @return
* @throws IOException
*/
public static String writeToStr(Object obj) throws IOException {
// 此類實現了一個輸出流,其中的數據被寫入一個 byte 數組。
// 緩沖區會隨著數據的不斷寫入而自動增長。可使用 toByteArray() 和 toString() 獲取數據。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 專用於java對象序列化,將對象進行序列化
ObjectOutputStream objectOutputStream = null;
String serStr = null;
try {
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
serStr = byteArrayOutputStream.toString(TEMP_ENCODING);
serStr = java.net.URLEncoder.encode(serStr, DEFAULT_ENCODING);
} catch (IOException e) {
e.printStackTrace();
} finally {
objectOutputStream.close();
}
return serStr;
}


/**
* 把字符串反序列化java對象
* @param serStr
* @return
* @throws IOException
*/
public static Object deserializeFromStr(String serStr) throws IOException {
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
String deserStr = java.net.URLDecoder.decode(serStr, DEFAULT_ENCODING);
byteArrayInputStream = new ByteArrayInputStream(deserStr.getBytes(TEMP_ENCODING));
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
objectInputStream.close();
byteArrayInputStream.close();
}
return null;
}

Copyright © Linux教程網 All Rights Reserved