Base64 Encoding and Decoding in Java 8

In this post, we’ll discuss Base64 Encoding and Decoding in Java 8.


 

Java 8 finally extended support for Base64 Encoding and Decoding capabilities, by providing Base64, Base64.Encoder and Base64.Decoder utility class in the java.util package. Base64 class consists of static methods for obtaining instances of encoders (Base64.Encoder) and decoders (Base64.Decoder) for the Base64 encoding scheme.

 
The implementation of Base64 class supports the following types of encodings:

 

1. The Basic Encoding

The basic encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet set which is A-Za-z0-9+/.

Below program uses Base64.Encoder.encodeToString() method for encoding the specified byte array into a Base64 encoded String and Base64.Decoder.decode() method for decoding back the Base64 encoded String into a newly-allocated byte array.

We can also use Base64.Encoder.encode() method for writing the resulting bytes to a byte array, instead of a String.

 

Download   Run Code

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 

The basic encoding adds padding character at the end of the encoded byte data by default if the length of the encoded String is not a multiple of 3. These padding characters is then discarded on decoding. To get an encoder without padding, we can call withoutPadding() method:

 

 

2. The URL and Filename safe Encoding

To encode an URL, we can’t use basic encoding. We should use the “URL and Filename safe Base64 Alphabet” for encoding and decoding. The encoder does not add any line feed (line separator) character and the decoder rejects data that contains characters outside the base64 alphabet.

The following example encodes an url using the URL encoder:

 

Download   Run Code

Output:

Using URL Alphabet: aHR0cDovL3d3dy50ZWNoaWVkZWxpZ2h0LmNvbS8_dj0x
http://www.techiedelight.com/?v=1

 

3. The MIME Encoding

The MIME Encoding uses the “The Base64 Alphabet” for encoding and decoding operation but the encoded output is represented in lines of no more than 76 characters each and uses a carriage return followed by a linefeed '\r\n' as the line separator.

The following example encodes an large block of text (having more than 76 characters) using the MIME encoder:

 

Download   Run Code

Output (may vary):

e2317f97-47d0-4799-b383-2a89070d5c1ef57d1659-3153-47d6-88a1-be3d5cca8cf526afb83c-c0db-4ef6-bd41-edc7ca4a691db744a484-f6fd-4f80-a7e4-4d8d3d7d3153309b3b8c-d4b3-4027-821b-85450c735616

 

 
References: Base64 (Java Platform SE 8)

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz