Java : Base64.Decoder - API Examples

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


Class diagram

Class diagram

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