Decode Base64 data in Java

前端 未结 20 1451
时光说笑
时光说笑 2020-11-21 06:04

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.

20条回答
  •  情书的邮戳
    2020-11-21 06:49

    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.

提交回复
热议问题