1.

Inbuilt encoder and decoder for Base64 encoding in Java 8

Answer»

The BASE64 class consist of static methods for obtaining encoders and decoders for Base64 encoding. JAVA 8 allows us to use three types of encoding:

  • Basic − The output is plotted to a set of characters lying in Base64 alphabet. The encoder does not add any line feed in output, and the decoder rejects any character other than Base64 alphabet.
  • Uniform Resource Locator(URL) and filename safe − The output is plotted to set of characters lying in Base64 alphabet. The decoder rejects data that contains characters outside the Base64 alphabet.
  • Multipurpose Internet Mail Extensions (MIME) − The output is plotted to MIME compatible format. The encoded output must have lines with a maximum of 76 characters each and applies a carriage return '\r' followed instantly by a linefeed '\n' as the line separator. There is no linefeed separator at the end of the encoded output. All the characters apart from the Base64 alphabet are IGNORED by the decoder.

The declaration of the Base64 class is as follows:

public class Base64 EXTENDS Object

Let us see an example of basic Base64 encoding and decoding:

import java.util.Base64; public class Example {    public static void main(String[] args)    {        String enc = Base64.getEncoder().encodeToString("Encoding in Base64".getBytes());        System.out.println("Encoder Output : " + enc);        byte[] dec = Base64.getDecoder().decode(enc);       System.out.println("Decoder Output : " + new String(dec));    } }

The output is as follows:

$javac Example.java $java -Xmx128M -Xms16M Example Encoder Output : RW5jb2RpbmcgaW4gQmFzZTY0 Decoder Output : Encoding in Base64


Discussion

No Comment Found