temporaneità

English scratches and Italian notes written by Carlo Perassi

Menu Close

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.