Java Base64Variant-class And Method Code Example


Here's an example of how to use the Base64Variant class from the Apache Commons IO library to encode a string to a base64 variant:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64Variant;

public class Main {
    public static void main(String[] args) {
        String originalString = "Hello World";
        byte[] originalBytes = originalString.getBytes();

        Base64Variant variant = Base64Variant.getDefaultVariant();
        byte[] encodedBytes = Base64.encodeBase64(originalBytes, variant);

        String encodedString = new String(encodedBytes);
        System.out.println(encodedString);
    }
}

The above example uses the default variant of base64, but you can also specify a different variant by passing the appropriate Base64Variant object to the Base64.encodeBase64 method.

To decode the encoded string back to its original form, you can use the following code:

byte[] decodedBytes = Base64.decodeBase64(encodedBytes, variant);
String decodedString = new String(decodedBytes);
System.out.println(decodedString);

This will output the original string "Hello World"