I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.
No need to use commons--Sun ships a base64 encoder with Java. You can import it as such:
import sun.misc.BASE64Decoder;
And then use it like this:
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
Where encodedBytes
is either a java.lang.String
or a java.io.InputStream
. Just beware that the sun.*
classes are not "officially supported" by Sun.
EDIT: Who knew this would be the most controversial answer I'd ever post? I do know that sun.* packages are not supported or guaranteed to continue existing, and I do know about Commons and use it all the time. However, the poster asked for a class that that was "included with Sun Java 6," and that's what I was trying to answer. I agree that Commons is the best way to go in general.
EDIT 2: As amir75 points out below, Java 6+ ships with JAXB, which contains supported code to encode/decode Base64. Please see Jeremy Ross' answer below.