Java Base64 getDecoder()

In this guide, you will learn about the Base64 getDecoder() method in Java programming and how to use it with an example.

1. Base64 getDecoder() Method Overview

Definition:

The getDecoder() method of the Base64 class in Java is a static method that returns a Base64.Decoder. This decoder is used to decode data encoded with the Basic type base64 encoding scheme. The method belongs to the java.util package, providing a mechanism to decode base64 encoded strings as per RFC 4648.

Syntax:

public static Base64.Decoder getDecoder()

Parameters:

- The method does not take any parameters.

Key Points:

- The getDecoder() method does not throw any exceptions.

- It returns a Base64.Decoder for decoding base64 encoded data using the Basic type base64 encoding scheme.

- The decoder discards whitespace from the input as per the specifications of RFC 2045.

2. Base64 getDecoder() Method Example

import java.util.Base64;

public class Base64DecoderExample {

    public static void main(String[] args) {
        // Get a Base64.Decoder
        Base64.Decoder decoder = Base64.getDecoder();

        // Input base64 encoded data
        String encodedData = "SmF2YSBCYXNlNjQgRGVjb2RpbmcgRXhhbXBsZQ==";

        // Decode the input data
        byte[] decodedData = decoder.decode(encodedData);

        // Convert the decoded byte array to a string
        String originalData = new String(decodedData);

        // Print the original data
        System.out.println("Original Data: " + originalData);
    }
}

Output:

Original Data: Java Base64 Decoding Example

Explanation:

In this example, a Base64.Decoder object is obtained using the getDecoder() method. We then provided a base64 encoded string, decoded it using the decode() method of the Base64.Decoder object, and converted the resulting byte array back to a string. Finally, the original data is printed to the console, showcasing the decoding process.

Comments