Chunking Base64 binary data in Java
I’m not an expert but it seems to me that the different methods to encode as Base64 a *binary* stream exposed by Apache Commons don’t chunk for binary inputs or don’t chunk at all, in spite of what their documentation states.
So let me write here a little snippet, which uses guava-libraries, for an already getBytes()-ed string.
private static String b64eChunk(String mstring) {
String encodedText = Base64.encodeBase64String(mstring.getBytes());
String myOutput = "";
for (String substring : Splitter.fixedLength(76).split(encodedText)) {
myOutput += substring + "\n";
}
return myOutput.substring(0, myOutput.length() - 1);
}
Credits for the guava part: Cowan.
String building using concatenation is not efficient. You should a StringBuilder instead. But even better, in this example you’re joining strings together, so you can use Guava’s Joiner:
return Joiner.on(‘\n’).join(Splitter.fixedLength(76).split(encodedText));
Also, calling getBytes() on String is usually wrong as it uses the platform default character encoding, which means you get different results on different platforms. You usually want getBytes(Charsets.UTF_8)).
Thanks. Perhaps deleting this post won’t be a bad idea because after publishing it I’ve learned a few things about Apache Commons.