Java object --- serialization and deserialization, java object --- serialization
Private static final String TEMP_ENCODING = "ISO-8859-1 ";
Private static final String DEFAULT_ENCODING = "UTF-8 ";
/**
* Serialize a java object to a string
* @ Param obj
* @ Return
* @ Throws IOException
*/
Public static String writeToStr (Object obj) throws IOException {
// This class implements an output stream, where data is written into a byte array.
// The buffer will automatically increase as data is constantly written. You can use toByteArray () and toString () to obtain data.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ();
// Special for java object serialization, serialization of Objects
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;
}
/**
* Deserializes a string from a java object
* @ 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;
}