Java : Base64 with Examples
Base64 (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Base64 methods.
Summary
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final var dst = encoder.encodeToString(src);
System.out.println(dst); // AQIDBAUGBw==
final var decoder = Base64.getDecoder();
final var decoded = decoder.decode(dst);
System.out.println(Arrays.toString(decoded)); // [1, 2, 3, 4, 5, 6, 7]
Methods
static Base64.Decoder getDecoder ()
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final var dst = encoder.encodeToString(src);
System.out.println(dst); // AQIDBAUGBw==
final var decoder = Base64.getDecoder();
final var decoded = decoder.decode(dst);
System.out.println(Arrays.toString(decoded)); // [1, 2, 3, 4, 5, 6, 7]
static Base64.Encoder getEncoder ()
Please see getDecoder().
static Base64.Decoder getMimeDecoder ()
final var src = new byte[130];
for (int i = 0; i < src.length; i++) {
src[i] = (byte) (i % 100);
}
// [0, 1, 2, 3, 4, ... 96, 97, 98, 99, 0, 1, 2, ... 25, 26, 27, 28, 29]
System.out.println(Arrays.toString(src));
{
final var encoder = Base64.getMimeEncoder();
final var dst = encoder.encodeToString(src);
// The encoder for MIME results lines of no more than 76 characters each.
// AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4
// OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiYwABAgMEBQYHCAkKCwwN
// Dg8QERITFBUWFxgZGhscHQ==
System.out.println(dst);
final var decoder = Base64.getMimeDecoder();
final var decoded = decoder.decode(dst);
System.out.println(Arrays.equals(src, decoded)); // true
}
{
final var encoder = Base64.getEncoder();
final var dst = encoder.encodeToString(src);
// The normal encoder results one line.
// AAECAwQFBgc ... xgZGhscHQ==
System.out.println(dst);
}
static Base64.Encoder getMimeEncoder ()
Please see getMimeDecoder().
static Base64.Encoder getMimeEncoder (int lineLength, byte[] lineSeparator)
final byte[] src = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
final var encoder = Base64.getMimeEncoder(8, " ".getBytes());
final var dst = encoder.encodeToString(src);
// AQIDBAUG BwgJCgsM DQ==
System.out.println(dst);
static Base64.Decoder getUrlDecoder ()
final byte[] src = {105, -65, -65, 113};
{
// The normal encoder.
final var encoder = Base64.getEncoder();
final var dst = encoder.encodeToString(src);
// ab+/cQ==
System.out.println(dst);
}
{
// The encoder for URL and Filename safe.
final var encoder = Base64.getUrlEncoder();
final var dst = encoder.encodeToString(src);
// ab-_cQ==
System.out.println(dst);
final var decoder = Base64.getUrlDecoder();
final var decoded = decoder.decode(dst);
// [105, -65, -65, 113]
System.out.println(Arrays.toString(decoded));
}
static Base64.Encoder getUrlEncoder ()
Please see getUrlDecoder().
Related posts
- API Examples