Monday, April 24, 2023

How to Base 64 Encoding Decoding in Java 8 - Example Tutorial

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and its Base64 class to encode or decode binary data into base 64 encoding, as shown here, or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which was not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. 

This class contains methods like getEncoder() and getDecoder() to provide Base64 encoder and decoder to carry out base 64 encodings of String or binary data.

In this article, I'll show you some examples of how to base64 encode String in Java 8. Java 8 provides three types of base64 encoding and corresponding built-in encoder and decoder, as shown below.

1. Basic Base64 Encoder

In this type of encoder, only characters A-Z a-z0-9+/ are used for base64 encoding. The encoder does not add any line feed in the output, and the decoder rejects any character other than A-Za-z0-9+/. That's why you see a big line of alphanumeric characters. This is the one you will use most likely and we'll see examples of this Base64 encoder in this tutorial.

You can use the static getEncoder() and getDecoder() method of Base64 class to obtain the basic base64 encoder and decoder and use their encode() and decode()  for base64 encoding and decoding.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.




2. URL Base64 Encoder

This is similar to basic type but instead of "\", underscore ("_") is used i.e. only characters A-Za-z0-9+_ are supported. The key point about this encoder is that output is also URL and filename safe because there is no "\" character which acts as the path separator in many operating systems e.g. Windows.

You can use the getUrlEncoder() and getUrlDecoder() method to get the encoder and decoder who can perform this type of base64 encoding. See here to learn more about URL base64 encoder which is immensely helpful for Java web applications.



3. MIME Base64 Encoder

This is the third type of base64 encoding supported by Java 8. In this case, the output is mapped to the MIME-friendly format. The 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 at the end of the encoded output.

You can use the static method getMimeEncoder() and getMimeDecoder() to get the MIME type base64 encoder and decoder with specified line length and line separators. Please see Java SE8 for Programmers (3rd Edition) by Dietel and Deitel to learn more about these advanced base64 encoders and decoders.



Base64 Encoding Example in Java 8

Now, let's an example of how to encode String into base64 encoding in Java 8. Here is our sample Java program which demonstrates base64 encoding and decoding in basic, URL, and MIME types. Read, Java SE 8 for Really Impatient for more details.


For those who are not very familiar with base64 encoding in general, here is a good slide to recap the fundamentals:

Base64 Encoding Decoding Example in Java 8



Java program for base64 encoding and decoding String

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

/*
 * Java Program to Base64 encode a String in JDK 8. 
 * 
 */
public class PascalTriangleInJava {

    public static void main(String[] args) {

        // Encoding String using basic base64 encoder
        Encoder theEncoder = Base64.getEncoder();
        String original = "Minecraft";
        byte[] theArray = original.getBytes(StandardCharsets.UTF_8);
        String base64encodedString = theEncoder.encodeToString(theArray);
        System.out.println("Original String: " + original);
        System.out.println("Base64 Encoded String :" + base64encodedString);

        // Decoding a base64 encoded String in Java 8
        Decoder theDecoder = Base64.getDecoder();
        byte[] byteArray = theDecoder.decode(base64encodedString);
        String decoded = new String(byteArray, StandardCharsets.UTF_8);
        System.out.println("decoded String: " + decoded);

    }

}


Output
Original String: Minecraft
Base64 Encoded String :TWluZWNyYWZ0
decoded String: Minecraft


That's all about how to encode String in base64 in Java 8. Now, there is no need to use the Apache commons Code library (an additional dependency on the third-party library) or non-standard sun.misc.BASE64Encoder class for base64 encoding.

You should only use the new java.util.Base64 class for encoding and decoding String or byte array into Base64. In the next part of this article, I'll teach you how to decode a Base64 encoded String in Java 8. You can also join these Java 8 online courses to learn more about these useful utilities.


Other Java 8 tutorials you may like to explore
  • 10 Example of Lambda Expression in Java 8 (see here)
  • 10 Example of Joining String in Java 8 (tutorial)
  • 10 Example of Stream API in Java 8 (see here)
  • 5 OCAJP8 books for Java developers (list)
  • 10 Example of forEach() method in Java 8 (example)
  • Difference between map() and flatMap() in Java 8 (tutorial)
  • 10 Example of converting a List to Map in Java 8 (example)
  • How to use Stream.map() in Java 8 (example)
  • How to use Stream.flatMap in Java 8(example)
  • 20 Example of LocalDate and LocalTime in Java 8 (see here)
  • 5 Books to Learn Java 8 and Functional Programming (list)


Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions, doubts, or feedback then please drop a comment and I'll try to answer your question.

2 comments :

Ghochu said...

Very good information. Thanks for your effort.

Unknown said...

Thank you :)

Post a Comment