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);
}
}
Output
base64 Encoded String:
rO0ABXNyABNqYXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAEdwQAAAAK
dAABMXQADXNlY29uZCBPYmplY3R0AAlLcmlzaG5hIDN0AARsYXN0eA==
ArrayList values:
[1, second Object, Krishna 3, last]
No comments:
Post a Comment