CSS

Thursday, March 30, 2017

Java Base64 OutputStream cutting off characters

This took me a while to figure out. I am using a Outputstream to write create a piece of XML.  One of the elements needed to be Base64 encoded.  I wrapped my outputstring using java.util.Base64.wrap.  I did not close the Base64 OutputStream.  It is not really clear but the close of this stream is when it takes care of padding,

Bad Code

// out is a FileOutputStream 
final Base64.Encoder encoder = Base64.getMimeEncoder(); 
final OutputStream clob = encoder.wrap(out); 
IOUtils.copy(in, clob, Charset.forName("UTF-8")); 
// No close of clob Just went and kept writing to out 

Good Code

// out is a FileOutputStream 
final Base64.Encoder encoder = Base64.getMimeEncoder(); 
final OutputStream clob = encoder.wrap(
      new CloseShieldOutputStream(out)); // Use nice Apache IO Wrapper that does                        // not chain close 
IOUtils.copy(in, clob, Charset.forName("UTF-8")); 
clob.close(); // this forces out the padding