1. Introduction
Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used to encode binary data, such as images or files, to be transmitted over media that are designed to deal with textual data. In this guide, we will explore how to encode a String using Base64 in Java.
2. Program Steps
1. Define the input String that you want to encode.
2. Convert the input String into a byte array.
3. Encode the byte array using the Base64 class provided by Java.
4. Convert the encoded byte array back to a String.
5. Print the original and the encoded String.
3. Code Program
import java.util.Base64;
public class Base64Encode {
public static void main(String[] args) {
// Step 1: Define the input String
String originalString = "JavaProgramming!";
// Step 2: Convert the input String into a byte array
byte[] inputBytes = originalString.getBytes();
// Step 3: Encode the byte array using Base64
byte[] encodedBytes = Base64.getEncoder().encode(inputBytes);
// Step 4: Convert the encoded byte array back to a String
String encodedString = new String(encodedBytes);
// Step 5: Print the original and the encoded String
System.out.println("Original String: " + originalString);
System.out.println("Encoded String: " + encodedString);
}
}
Output:
Original String: JavaProgramming! Encoded String: SmF2YVByb2dyYW1taW5nIQ==
4. Step By Step Explanation
– Step 1: We start by defining the original String originalString that we want to encode using Base64.
– Step 2: The original String is converted to a byte array inputBytes using the getBytes() method.
– Step 3: Java provides a Base64 class that contains a method getEncoder().encode() which is used to encode the byte array inputBytes.
– Step 4: The encoded byte array encodedBytes is then converted back to a String encodedString.
– Step 5: Finally, we print out the original and the encoded String to the console.