Base64 Encoding in Mercury
Our program demonstrates base64 encoding and decoding in Java. Here’s the full source code:
Java provides built-in support for base64 encoding/decoding through the java.util.Base64
class. This class offers both standard and URL-compatible base64 encoders and decoders.
To run the program, compile and execute it:
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.
In Java, we use the Base64.getEncoder()
and Base64.getDecoder()
methods for standard base64 encoding and decoding. For URL-safe base64, we use Base64.getUrlEncoder()
and Base64.getUrlDecoder()
.
The encodeToString()
method is used to encode a byte array to a base64 string, while decode()
is used to decode a base64 string back to a byte array.
Note that in Java, we need to explicitly convert between strings and byte arrays using getBytes()
and the String
constructor.
Also, unlike in some other languages, Java’s base64 decoder throws an IllegalArgumentException
if the input is not properly formatted. It’s a good practice to catch this exception when decoding user input or data from untrusted sources.