Decode Base64 data in Java

前端 未结 20 1486
时光说笑
时光说笑 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:37

    As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().

    public static byte[] encode(byte[] b) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b);
        b64os.close();
        return baos.toByteArray();
    }
    public static byte[] decode(byte[] b) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        InputStream b64is = MimeUtility.decode(bais, "base64");
        byte[] tmp = new byte[b.length];
        int n = b64is.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return res;
    }
    

    Link with full code: Encode/Decode to/from Base64

提交回复
热议问题