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
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)
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)
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)
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)
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)
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
- API Examples