Java 8 Base64

Java 8 Base64 provides a standard way to do Base64 encoding and decoding.
There are three types of Base64 encoding:
Basic: Encoder produces a set of characters within A-Za-z0-9+/. Decoder rejects any character NOT mapped to A-Za-z0-9+/.
URL: Encoder produces a URL or safe filename which is set of characters within A-Za-z0-9+_.
MIME: Output is mapped to MIME friendly format.

I. Basic


String original = "Learn Java at javasampleapproach is great";

// Encode using basic encoder
String base64encodedString = Base64.getEncoder().encodeToString(original.getBytes("utf-8"));
System.out.println(base64encodedString);
// Result: TGVhcm4gSmF2YSBhdCBqYXZhc2FtcGxlYXBwcm9hY2ggaXMgZ3JlYXQ=

// Decode
byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
System.out.println(new String(base64decodedBytes, "utf-8"));
// Result: Learn Java at javasampleapproach is great

II. URL


String originalUrl = "grokonez.com/java?category=java8";

// Encode
base64encodedString = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes("utf-8"));
System.out.println(base64encodedString);
// Result: SmF2YVNhbXBsZUFwcHJvYWNoLmNvbS9qYXZhP2NhdGVnb3J5PWphdmE4

// Decode
base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString);
System.out.println(new String(base64decodedBytes, "utf-8"));
// Result: grokonez.com/java?category=java8

II. MIME


StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < 10; ++i) {
	stringBuilder.append(UUID.randomUUID().toString());
}

byte[] mimes = stringBuilder.toString().getBytes("utf-8");

// Encode
String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimes);
System.out.println(mimeEncodedString);

The result is:


MzRhZTllNWEtNTA3My00NWY3LWJlOTktZmY3OWUwY2MxZTIzMmRlMGFmMGQtODU4Mi00MjI1LWEz
MjItMjM2MmZlNDQyNjAzNmVjYjE2NzgtZTVhZC00NTg0LWFhMDQtNDQwMmEyZTYzOWNhNTNjYTFh
MjgtMGQxNi00ZDkyLWIxODctMzcyMDI1MzhhNDJmZGQ4ZDE0ZjQtYmFjZC00ZThhLWE0ZGQtODZm
MGQxMjY5YTEzN2FhYTZkZjktM2YwOS00MTZmLWE3YjMtMTg2NDI4ZTMzNzk4YzcwOGVmMjktOTFm
ZC00YTMyLTk4NjAtNjZhNmYwYWRmYmIxOTA2ZGJkNjEtNGQ1Yi00OWIwLWJkYjktOWMwNjY1MjU5
ZGZiYzM4YjY1ZmItODFmYi00NDI5LTk4ODctYzE0YjVhOTYyOTViZWY5OTY0NmItOTkzZS00ZmRm
LTk4ODctZDI1MzQwNDBkYTg1


By grokonez | December 21, 2016.

Last updated on April 19, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*