Open In App

Base64 Java Encode and Decode a String

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Base64 encoding allows encoding binary data as text strings for safe transport, at the cost of larger data size. It is commonly used when there is a need to encode binary data that needs to be stored or transferred via media that are designed to deal with textual data (like transporting images inside an XML, JSON document, etc.).

How to Convert a String to Base64 Encoded String in Java?

In Java, the java.util.Base64 class provides static methods to encode and decode between binary and base64 formats. The encode() and decode() methods are used.

Syntax:

String Base64format= Base64.getEncoder().encodeToString("String".getBytes());

Example to convert a String to base64 encoded String:

Java




// Java Program to Convert String 
// to Base64 Encoded String
import java.util.Base64;
  
public class Sample {
    public static void main(String[] args) {
         
        // Input string to be encoded
        String inputString = "GeeksForGeeks";
  
        // Creating Base64 encoder and decoder instances
        Base64.Encoder encoder = Base64.getEncoder();
        Base64.Decoder decoder = Base64.getDecoder();
  
        // Encoding the input string
        String encodedString = encoder.encodeToString(inputString.getBytes());
        
          System.out.println("Encoding Done:");
  
        // Displaying the original and encoded strings
        System.out.println("Original String: " + inputString);
        System.out.println("Base64 Encoded String: " + encodedString);
  
        // Decoding the Base64 encoded string
        byte[] decodedBytes = decoder.decode(encodedString);
        String decodedString = new String(decodedBytes);
        
        
          System.out.println("\nDecoding Done:");
  
        // Displaying the Base64 encoded and decoded strings
        System.out.println("Base64 Encoded String : " + encodedString);
        System.out.println("Original String: " + decodedString);
    }
}


Output

Encoding Done:
Original String: GeeksForGeeks
Base64 Encoded String: R2Vla3NGb3JHZWVrcw==

Decoding Done:
Base64 Encoded String : R2Vla3NGb3JHZWVrcw==
Original String: GeeksForGeeks

Explanation of the above Program:

  • It imports the Base64 class for encoding and decoding.
  • It encodes the input string to Base64 format and stores in a variable.
  • It decodes the Base64 encoded string back to original string.
  • It prints the original, encoded and decoded strings to verify it works.
  • The Base64 class provides easy methods to encode and decode strings in this format.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads