# Base64 encoding & decoding in Java

In 
Published 2023-06-07

This tutorial explains to you how to use the Base64 in Java. We have an example for you as well.

Base64 encoding takes as an input a string or a binary file and return a string of characters following a specific algorithm. This output string could have only some specific characters from a list of 64 characters. For the complete list you can go here.

This mechanism is useful in general when we want to convert a picture, an email attachments, an audio or a video file in text for sending it over the network. For restoring the content you use the decoder.

In Java 8, we can use 3 types of Base64 encoding.

  • Simple − the output contains a set of characters from A-Za-z0-9+/.
  • URL − the output contains a set of characters from in A-Za-z0-9+_. The output is an URL and filename safe.
  • MIME − the output is contains lines of no more than 76 characters each, and uses a carriage return '\r' followed by a linefeed '\n' as the line separator.

Before Java 8 this feature wasn't available.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

From the base application downloaded from Spring Initializr, I updated the main class as below:

DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Base64;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class, args);

		String myString = "Base64 is very useful.";
		System.out.println("myString = " + myString);

		// instantiate a Base64 simple encoder object
		Base64.Encoder encoder = Base64.getEncoder();

		// Encode myString
		String myStringEncoded = encoder.encodeToString(myString.getBytes());
		System.out.println("myStringEncoded = " + myStringEncoded);

		// instantiate a Base64 simple decoder object
		Base64.Decoder decoder = Base64.getDecoder();

		// Deconding the encoded string using decoder
		String decodedString = new String(decoder.decode(myStringEncoded.getBytes()));
		System.out.println("Decoded String : "+decodedString);
	}
}

When I run this code I get the following log:

myString = Base64 is very useful.
myStringEncoded = QmFzZTY0IGlzIHZlcnkgdXNlZnVsLg==
Decoded String : Base64 is very useful.

Process finished with exit code 0