adam bien's blog

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.