Wednesday, September 15, 2010

ObjectOutputStream with base64 Encoding

ObjectOutputStream with base64 Encoding

Most of the time we do write simplestic code to persist object state using ObjectOutputStream. This will work most of the serializable objects, however some cases serialized objects comes with multi-byte character. In this case, while converting persisted object to java object, we end up seeing weired exception message. To avoid this inconsistent, we have to get a help of any encoder. I have tried with base64 encoding mechanism, I did not face any issues.

Please follow the link, which explains with a sample of no encoding used to persist Java Objects

javax.mail.internet.MimeUtility class helps to encode/decode in base63 format. Generally, this class comes as part of mail.jar as a java extension tool.

import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.MimeUtility;

public class ObjectStreamBase64Test {
public static void main(String[] args) throws Exception {
List emp = new ArrayList();
emp.add("second Object");
emp.add("Krishna 3");

ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStream mout = MimeUtility.encode(bos, "base64");
ObjectOutputStream out = new ObjectOutputStream(mout);

byte[] bytes = bos.toByteArray();
String str = new String(bytes);

System.out.println("base64 Encoded String: \n"+str);

ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
ObjectInputStream in = new ObjectInputStream(MimeUtility.decode(bis,
Object obj = in.readObject();
ArrayList emp1 = (ArrayList) obj;
System.out.println("\nArrayList values:\n"+emp1);

Spring Recipes: A Problem-Solution Approach, Second Edition


base64 Encoded String: 

ArrayList values:
[1, second Object, Krishna 3, last]

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts


This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer