Base64 Java Encode and Decode a String
Last Updated :
31 Jan, 2024
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
import java.util.Base64;
public class Sample {
public static void main(String[] args) {
String inputString = "GeeksForGeeks" ;
Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();
String encodedString = encoder.encodeToString(inputString.getBytes());
System.out.println( "Encoding Done:" );
System.out.println( "Original String: " + inputString);
System.out.println( "Base64 Encoded String: " + encodedString);
byte [] decodedBytes = decoder.decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println( "\nDecoding Done:" );
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.
Share your thoughts in the comments
Please Login to comment...