Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Base64 encode a Java object using org.apache.commons.codec.binary.base64?

Tags:

People also ask

Can Base64 encode binary?

The base64 is a binary to a text encoding scheme that represents binary data in an ASCII string format. base64 is designed to carry data stored in binary format across the channels. It takes any form of data and transforms it into a long string of plain text.

What is Base64 encoding in Java?

What is Base64? Base64 is a binary-to-text encoding scheme that represents binary data in a printable ASCII string format by translating it into a radix-64 representation. Each Base64 digit represents exactly 6 bits of binary data.


I've been trying to do an object serialization and Base64 encode the result. It works with Sun's lib:

Bean01 bean01 = new Bean01();
bean01.setDefaultValues();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream( baos ).writeObject( bean01 );
System.out.println(Base64.encode(baos.toByteArray()));

This works fine. However, I would like to do the same using org.apache.commons.codec.binary.base64, but this does not return the same string:

System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));

What would be the correct way to achieve the correct Base64 encoding of a byteArray using Apache's encoder?