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.

0

There are 0 answers