Java 8 Base64 Encoding / Decoding

Java 8 comes with the Base64 class which supports Base64 encoding / decoding out-of-the-box:


import java.util.Base64;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;

public class Base64Test {

    @Test
    public void encodeAndDecode() {
        final String rawString = "duke";
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encodedContent = encoder.encode(rawString.getBytes());

        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decodedContent = decoder.decode(encodedContent);

        String decodedString = new String(decodedContent);
        assertThat(decodedString, is(rawString));
    }
}

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

Just a couple of days earlier I was researching Base64 utility area. Here are my results:

https://artofcode.wordpress.com/2017/01/10/base64-for-java/

The Base64 util built in Java 8 is nice but it's not as useful/comfortable as it could be.

Posted by Krzysztof Tomaszewski on January 16, 2017 at 11:02 AM CET #

If you're using older JDKs you can also use the printBase64Binary(byte[]) and parseBase64Binary(String) methods in javax.xml.bind.DatatypeConverter.

Posted by Stephen Coy on January 18, 2017 at 01:31 PM CET #

Hello Adam,
do you know if the Java 8 base64 encoding/decoding is compatible with sun.misc.BASE64Encoder and sun.misc.BASE64Decoder? Is it save to switch to Java 8 base64 encoding/decoding if our project is using the Sun encoders/decoders?

Posted by Roman on January 19, 2017 at 10:28 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License