Java object --- serialization and deserialization, java object --- serialization

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.