I'm using Eclipse. I have the following line of code:
wr.write(new sun.misc.BASE64Encoder().encode(buf));
Eclipse marks this line as an error. I imported the required libraries:
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
But again, both of them are shown as errors. I found a similar post here.
I used Apache Commons as the solution suggested by including:
import org.apache.commons.*;
and importing the JAR files downloaded from: http://commons.apache.org/codec/
But the problem still exists. Eclipse still shows the errors previously mentioned; please advise.
Google Guava is a good choice to encode and decode base64 data:
POM config:
Sample code:
Here are my two cents... Java 8 does contain its own implementation of
Base64
. However, I found one slightly disturbing difference. To illustrate, I will provide a code example:My CODEC wrapper:
Test Class:
OUTPUT:
Notice that the Apache encoded text contain additional line breaks (white spaces) at the end. Therefore, in order for my CODEC to yield the same result regardless of Base64 implementation, I had to call
trim()
on the Apache encoded text. In my case, I simply added the aforementioned method call to the my CODEC'sapacheDecode()
as follows:Once this change was made, the results are what I expected to begin with:
Maybe someone could comment as to why this is, but I found my workaround as an acceptable compromise.
Simple example with Java 8:
You can also convert using base64 encoding. To do this you can use
javax.xml.bind.DatatypeConverter#printBase64Binary
methodFor example:
For java 6-7 best option is to borrow code from Android repository. It has no dependencies.
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Base64.java
On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Froyo).