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.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
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("1");
emp.add("second Object");
emp.add("Krishna 3");
emp.add("last");

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

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,
"base64"));
Object obj = in.readObject();
ArrayList emp1 = (ArrayList) obj;
System.out.println("\nArrayList values:\n"+emp1);

}
}
Spring Recipes: A Problem-Solution Approach, Second Edition

Output

base64 Encoded String: 
rO0ABXNyABNqYXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAEdwQAAAAK
dAABMXQADXNlY29uZCBPYmplY3R0AAlLcmlzaG5hIDN0AARsYXN0eA==

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

Recent Posts

Unix Commands | List all My Posts

Texts

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 blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More