Java : Base64.Decoder with Examples

Base64.Decoder (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Base64.Decoder methods.


Summary

This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Class diagram

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

byte[] decode (byte[] src)

Decodes all bytes from the input byte array using the Base64 encoding scheme, writing the results into a newly-allocated output byte array.

final var decoder = Base64.getDecoder();

final var src = "AQIDBAUGBw==".getBytes();
final var dst = decoder.decode(src);

System.out.println(Arrays.toString(dst)); // [1, 2, 3, 4, 5, 6, 7]

int decode (byte[] src, byte[] dst)

Decodes all bytes from the input byte array using the Base64 encoding scheme, writing the results into the given output byte array, starting at offset 0.

final var decoder = Base64.getDecoder();

final var src = "AQIDBAUGBw==".getBytes();
final byte[] dst = new byte[src.length]; // With a little margin.

final var size = decoder.decode(src, dst);
System.out.println(size); // 7

System.out.println(Arrays.toString(dst)); // [1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0]

byte[] decode (String src)

Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme.

final var decoder = Base64.getDecoder();

final var src = "AQIDBAUGBw==";
final var dst = decoder.decode(src);

System.out.println(Arrays.toString(dst)); // [1, 2, 3, 4, 5, 6, 7]

ByteBuffer decode (ByteBuffer buffer)

Decodes all bytes from the input byte buffer using the Base64 encoding scheme, writing the results into a newly-allocated ByteBuffer.

final var decoder = Base64.getDecoder();

final var src = "AQIDBAUGBw==".getBytes();
final var srcBuffer = ByteBuffer.wrap(src);

final var dstBuffer = decoder.decode(srcBuffer);
System.out.println(dstBuffer); // java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]

final var dst = dstBuffer.array();
System.out.println(Arrays.toString(dst)); // [1, 2, 3, 4, 5, 6, 7]

InputStream wrap (InputStream is)

Returns an input stream for decoding Base64 encoded byte stream.

final var path = Path.of("R:", "java-work", "sample.txt");
System.out.println(path); // R:\java-work\sample.txt

Files.writeString(path, "AQIDBAUGBw==");

final var decoder = Base64.getDecoder();

try (final var inputStream = decoder.wrap(Files.newInputStream(path))) {

    final var dst = inputStream.readAllBytes();
    System.out.println(Arrays.toString(dst)); // [1, 2, 3, 4, 5, 6, 7]
}

Related posts

To top of page