Java Base64 Encode and Decode Example

1. Introduction

Base64 encoding is a technique used to encode binary data into ASCII characters, commonly used in data transmission and storage solutions where binary data needs to be stored and transferred over media that are designed to deal with textual data. This tutorial covers how to encode and decode strings using Base64 in Java.

Key Points

1. Base64 encoding helps in transmitting binary data over text-based formats.

2. Java provides a built-in Base64 utility class starting from Java 8, simplifying encoding and decoding operations.

3. Encoding and decoding are reversible processes, where data is first encoded into Base64 format and then can be decoded back to its original form.

2. Program Steps

1. Import the necessary classes.

2. Define methods for encoding and decoding using Base64.

3. Encode a string and then decode it to verify that the original data is recovered.

3. Code Program

import java.nio.charset.StandardCharsets;
import java.util.Base64;

class Base64EncodeDecodeExample {

    private static String base64Decode(String value) {
        byte[] decodedValue = Base64.getDecoder().decode(value);
        return new String(decodedValue, StandardCharsets.UTF_8);
    }

    private static String base64Encode(String value) {
        return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) {
        String data = "https://www.sourcecodeexamples.net";

        String encodedData = base64Encode(data);
        System.out.println("encodedData -> " + encodedData);

        String decodedData = base64Decode(encodedData);
        System.out.println("decodedData -> " + decodedData);
    }
}

Output:

encodedData -> aHR0cHM6Ly93d3cuc291cmNlY29kZWV4YW1wbGVzLm5ldA==
decodedData -> https://www.sourcecodeexamples.net

Explanation:

1. base64Encode method uses Base64.getEncoder() to convert the input string into a Base64 encoded string. This is particularly useful for encoding data that needs to be sent over the internet.

2. base64Decode method uses Base64.getDecoder() to convert the Base64 encoded string back into the original string. This shows that the encoding process is reversible and lossless.

3. The output shows the encoded data as a Base64 string and then the decoded data, verifying that the original URL is preserved through the encode-decode cycle.


Comments