Java : Base64.Encoder with Examples
Base64.Encoder (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Base64.Encoder 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[] encode (byte[] src)
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final var dst = encoder.encode(src);
System.out.println(Arrays.toString(dst)); // [65, 81, 73, 68, 66, 65, 85, 71, 66, 119, 61, 61]
System.out.println(new String(dst)); // AQIDBAUGBw==
int encode (byte[] src, byte[] dst)
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final byte[] dst = new byte[src.length * 2 + 4]; // With a little margin.
final var size = encoder.encode(src, dst);
System.out.println(size); // 12
System.out.println(Arrays.toString(dst)); // [65, 81, 73, 68, 66, 65, 85, 71, 66, 119, 61, 61, 0, 0, 0, 0, 0, 0]
System.out.println(new String(dst, 0, size)); // AQIDBAUGBw==
ByteBuffer encode (ByteBuffer buffer)
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final var srcBuffer = ByteBuffer.wrap(src);
final var dstBuffer = encoder.encode(srcBuffer);
System.out.println(dstBuffer); // java.nio.HeapByteBuffer[pos=0 lim=12 cap=12]
final var dst = dstBuffer.array();
System.out.println(Arrays.toString(dst)); // [65, 81, 73, 68, 66, 65, 85, 71, 66, 119, 61, 61]
System.out.println(new String(dst)); // AQIDBAUGBw==
String encodeToString (byte[] src)
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==
Base64.Encoder withoutPadding ()
final var encoder1 = Base64.getEncoder();
final var encoder2 = encoder1.withoutPadding();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
final var dst1 = encoder1.encodeToString(src);
final var dst2 = encoder2.encodeToString(src);
System.out.println(dst1); // AQIDBAUGBw==
System.out.println(dst2); // AQIDBAUGBw
OutputStream wrap (OutputStream os)
final var path = Path.of("R:", "java-work", "sample.txt");
System.out.println(path); // R:\java-work\sample.txt
final var encoder = Base64.getEncoder();
final byte[] src = {1, 2, 3, 4, 5, 6, 7};
try (final var outputStream = encoder.wrap(Files.newOutputStream(path))) {
outputStream.write(src);
}
final var dst = Files.readString(path);
System.out.println(dst); // AQIDBAUGBw==
Related posts
- API Examples