Java 8 - Base64

With Java 8, Base64 has finally got its due. Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding.

  • Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.

  • URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe.

  • MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return '\r' followed by a linefeed '\n' as the line separator. No line separator is present to the end of the encoded output.

Methods Inherited

This class inherits methods from the following class −

  • java.lang.Object

Base64 Example

Create the following Java program using any editor of your choice in say C:/> JAVA.

        import java.util.Base64;
import java.util.UUID;

public class HelloWorld {

   public static void main(String args[]) {

      try {
         // Encode using basic encoder
         String base64encodedString = Base64.getEncoder().encodeToString(
         System.out.println("Base64 Encoded String (Basic) :" + base64encodedString);
         // Decode
         byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
         System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));
         base64encodedString = Base64.getUrlEncoder().encodeToString(
         System.out.println("Base64 Encoded String (URL) :" + base64encodedString);
         StringBuilder stringBuilder = new StringBuilder();
         for (int i = 0; i < 10; ++i) {
         byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
         String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
         System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);

      } catch(UnsupportedEncodingException e) {
         System.out.println("Error :" + e.getMessage());
Run example » It should produce the following output −
Base64 Encoded String (Basic) :VHV0b3JpYWxzUG9pbnQ/amF2YTg=
Original String: TutorialsPoint?java8
Base64 Encoded String (URL) :VHV0b3JpYWxzUG9pbnQ_amF2YTg=
Base64 Encoded String (MIME) :YmU3NWY2ODktNGM5YS00ODlmLWI2MTUtZTVkOTk2YzQ1Njk1Y2EwZTg2OTEtMmRiZC00YTQ1LWJl

javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition