Encoding and Decoding example in Java

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 it's Base64 class to encode or decode binary data into base 64 encoding or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which were 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 encoding of String or binary data. In this article, I'll show you some example 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.

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.

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.

MIME Base64 Encoder This is the third type of base64 encoding supported by Java 8. In this case, the output is mapped to 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 to 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.

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.

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

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;


*/ 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.

Related blog:

Spring rest interview questions

Spring boot interview questions

Recommended Posts

Encoding and Decoding example in Java
Change java encoding in windows
StringBuffer and StringBuilder Class in Java
Understanding equals and hashCode in Java
Hello world in Java and Gradle
Difference between final and Immutable in Java
Concurrency Method in Java with basic example
[Java] for Each and sorted in Lambda
Arrylist and linked list difference in java
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Java and JavaScript
XXE and Java
Pi in Java
FizzBuzz in Java
Regarding the transient modifier and serialization in Java
Create barcodes and QR codes in Java PDF
Detect similar videos in Java and OpenCV rev.2
Parallel and parallel processing in various languages (Java edition)
Difference between next () and nextLine () in Java Scanner
Differences in writing Java, C # and Javascript classes
Capture and save from selenium installation in Java
Detect similar videos in Java and OpenCV rev.3
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]
Distinguish between positive and negative numbers in Java
Java adds and removes watermarks in word documents
Detect similar videos in Java and OpenCV rev.1
Represents "next day" and "previous day" in Java / Android
Questions in java exception handling throw and try-catch
Upload and download notes in java on S3
Encrypt / decrypt with AES256 in PHP and Java
Generate OffsetDateTime from Clock and LocalDateTime in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
[Android / Java] Screen transition and return processing in fragments
I tried Mastodon's Toot and Streaming API in Java
Rock-paper-scissors app in Java
Java Enum utilization example
Write ABNF in Java and pass the email address
NVL-ish guy in Java
Combine arrays in Java
Getters and setters (Java)
"Hello World" in Java
Callable Interface in Java
[Java] Thread and Runnable
Java true and false
Comments in Java source
Organize builds in C ++ / Java and Win / Linux combinations