1

I'm currently using a stream based approach to convert incoming Base64 characters to a byte[] using the Apache commons-codec class org.apache.commons.codec.binary.Base64OutputStream.

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import org.apache.commons.codec.binary.Base64OutputStream;

public class Base64Extractor {
    private final ByteArrayOutputStream result;
    private final OutputStreamWriter sink;

    private Base64Extractor() {
        result = new ByteArrayOutputStream();
        sink = new OutputStreamWriter(new Base64OutputStream(result, false));
    }

    public byte[] getBytes() throws Exception {
        sink.flush();
        sink.close();
        return result.toByteArray();
    }

    public void feed(char[] textCharacters, int textStart, int textLength) throws Exception {
        sink.write(textCharacters, textStart, textLength);
    }
}

I feed the base64 characters bit by bit (from somewhere) into the OutputStreamWriter. When all necessary characters are transfered, I simply call getBytes() to get my byte[] without having to much memory occupied. IMHO this code is very clear and readable.

Recently I learned about the java.util.Base64 class and i now want to rely on JDK provided classes only. I want to keep the streaming approach because of ... reasons.

However java.util.Base64.getDecoder().wrap() is using an java.io.InputStream and honestly speaking, this confuses me.

How can I make use of java.util.Base64 instead of Base64OutputStream to decode a stream of base64 characters to a byte array?

Thank you in advance.

Danny
  • 11
  • 3
  • It's possible you _can't._ It looks like Java's API assumes you're always reading in chars and writing out bytes, not writing out chars. (I mean, you could probably make it work by creating your own "feedable" `InputStream`, but that just becomes a mess.) – Louis Wasserman May 22 '21 at 22:19
  • That said, you _can_ do decoding in a streaming way in general, you just can't do it this way: you have to restructure it from using a `feed` method to feeding it from an `InputStream`. – Louis Wasserman May 22 '21 at 22:21
  • @LouisWasserman Thank you for your opinion. So no _easy_ way to migrate to JDK internal classes here. – Danny May 26 '21 at 19:01

0 Answers0