Java : Base64.Decoder - API使用例
Base64.Decoder (Java SE 18 & JDK 18)の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。
概要
Base64.Decoderクラスは、Base64方式でテキストデータをバイナリデータにデコード(変換)します。
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]
メソッド
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]; // 少し余裕を持って確保
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]
}
関連記事
- API 使用例