Decode Base64 data in Java

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

    Given a test encode/decode example of javax.xml.bind.DatatypeConverter using methods parseBase64Binary() and printBase64Binary() referring to @jeremy-ross and @nightfirecat answer.

    @Test
    public void EncodeDecode() {
        //ENCODE
        String hello = "Hello World";
        byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
        String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
        LOGGER.info(hello + " encoded=> " + encodedHello);
    
        //DECODE
        byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
        String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
        LOGGER.info(encodedHello + " decoded=> " + helloAgain);
    
        Assert.assertEquals(hello, helloAgain);
    }
    

    Result:

    INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
    INFO - SGVsbG8gV29ybGQ= decoded=> Hello World
    

提交回复
热议问题